In my application I get output in the form of Json array as below
{Students: [{Name: Harry,Subject: maths,},
{Name:Ryan,Subject: Biology,},
{Name:James ,Subject: maths,}]}
From this array I want to remove the whole object based on the applied condition.
Lets say if Subject is "Biology" remove the whole object and return:
{Students: [{Name: Harry,Subject: maths,},
{Name:James ,Subject: maths,}]}
How can I achieve this using java programming.
If You have the class (I assume Student here) you can unmarshall the object list using a serialization/deserialization library like Jackson to a collection like List and then do simple list manipulation. Assuming you are receiving the JSON as a string named students
List<Student> list = mapper.readValue(students,
TypeFactory.defaultInstance().constructCollectionType(List.class, Student.class));
This should work.
Edit:
Since you asked for a version that reads JSON from a file, there you go:
public JSONArray getFilteredStudents(String jsonFilePath) throws Exception {
FileReader fileReader = new FileReader(jsonFilePath);
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(fileReader);
JSONArray students = (JSONArray) json.get("Students");
Iterator itr = students.iterator();
while (itr.hasNext()) {
JSONObject obj = (JSONObject) itr.next();
if (obj.get("Subject").equals("Biology")) {
itr.remove();
}
}
return students;
}
Download json-simple library from here.
Related
I'm trying to get a nested array from a json file, but I can't find a way to do it. What I want is a array with many other arrays. Using arr.toArray() I get a array with two strings one being "["user1", "name", "password"]" and "["user2", "name", "password"]". Is there a way to get an array with arrays?
{
"Users": {
"info": [
["user1", "name", "password"],
["user2", "name", "password"]
]
}
}
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("myPath"));
JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonObject1 = (JSONObject) jsonObject.get("User1");
JSONArray arr = (JSONArray) jsonObject1.get("info");
System.out.println(arr.toArray());
} catch (Exception e) {
e.printStackTrace();
}
}
I think you might be using one of the older JSON Libraries, I believe its the org.json.simple library. If this is going to be an important project, I'd recommend switching over to the Google GSON Library.
For now, Try Switching
JSONObject jsonObject1 = (JSONObject) jsonObject.get("User1");
to
JSONObject jsonObject1 = (JSONObject) jsonObject.get("Users");
this should fix some of your problems. In your JSON file, Users is the object you need to get in order to access the info Array.
in the mean time, here's a starting place for GSON
GSON tutorialspoint
https://www.tutorialspoint.com/gson/gson_quick_guide.htm
I have a goal to verify that certain JSON that I've got from RabbitMQ corresponds to one of expected JSONs in an array in a single file.
In other words, I need to verify that this JSON:
{
"networkCode":"network",
"programId":"92000"
}
is present in this JSON array:
[
{
"networkCode":"network",
"programId":"92000"
},
{
"networkCode":"network",
"programId":"92666"
}
]
Thank you very much for help!
Some part of my code
//GET DESIRABLE JSON
String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
JSONObject myJSON= new JSONObject(message);
//GET THE JSON ARRAYS FROM FILE
JSONParser parser = new JSONParser();
Object expectedJSONs= parser.parse(new FileReader("C:\\amqpclient\\src\\test\\java\\tradeDoubler\\ExpectedDTO.json"));
JSONArray expectedArray = (JSONArray) expectedJSONs;
JSONAssert.assertEquals(
myJSON, expectedArray , JSONCompareMode.LENIENT);
Compilation says that cannot resolve this
Exception in thread "main" java.lang.AssertionError: Expecting a JSON array, but passing in a JSON object
Org.json library is quite easy to use.
Example code below:
import org.json.*;
JSONObject obj = new JSONObject(" yourJSONObjectHere ");
JSONArray arr = obj.getJSONArray("networkArray");
for (int i = 0; i < arr.length(); i++)
{
String networkCode = arr.getJSONObject(i).getString("networkCode");
......
}
By iterating on your JSONArray, you can check if each object is equal to your search.
You may find more examples from: Parse JSON in Java
May I suggest you to use the Gson Library?
You can use something like this. But It will throw an exception if the json doesn't match/contains the fields.
Type listType = new TypeToken<ArrayList<YourJavaClassJsonModel>>() {
}.getType();
List<YourJavaClassJsonModel> resultList = gson.fromJson(JsonString, listType);
Hope it may help
You could use a JSON parser to convert the JSON to a Java object (Jackson and GSON are good options), and then check that object.
I am getting following output on console from the json post request in java using rest api.
{"id":"19494","key":"DF-1079","self":"http://sjira/rest/api/2/issue/19494"}
I need to take just key from this output and pass it on to other method using java.
You can use Gson library for json parsing.
This json library will convert json String to the Object you want. You want keys from it so you can get it parsed to a map and then get key set from it. Pass this key set to other method as per your need.
Code Example
Gson gson = new Gson();
String response= "{\"id\":\"19494\",\"key\":\"DF-1079\",\"self\":\"http://sjira/rest/api/2/issue/19494\"}";
//below line will parse your response to map
Map<String,Object> map = gson.fromJson(response, Map.class);
//get keyset from it pass to some method.
passToSomeMethod(map.keySet())
This keyset will be of type Set. Implementation in method to use it should be accordingly.
Done
You should use entrySet() on json object and populate a List which can be further used as argument in a method or anywhere.
JSONParser parser = new JSONParser();
JSONObject jObj = (JSONObject) parser.parse(postString); // postString contains your response string
List<String> keys = new ArrayList<String>();
for (Entry<String, JsonElement> e : jObj.entrySet()) {
keys.add(e.getKey());
}
Working on JSON for the first time. The problem is -
I am getting null pointer exception even after handling the empty json array.
I have created a josn file file in which there is an empty array. my json file is like-
{
"name" :"jsonObject",
"myArray" : []
}
For parsing I am using json.simple-1.1.1.jar.
My java code is -
JSONParser parser = new JSONParser();
JSONObject rootObj = (JSONObject) parser.parse(new FileReader(filePath));
String str = (String) rootObj.get("name");
JSONArray array = (JSONArray)rootObj.get("array");
if(array.isEmpty())
System.out.println("array is null");
In json file the array will be null sometimes and sometimes not. What is the proper way to handle it?
Your member's name is myArray not array. This works:
JSONArray array = (JSONArray) rootObj.get("myArray");
To check if the member is there use has():
if(rootObj.has("myArray")) {
JSONArray array = rootObj.getJSONArray("myArray"); // getJSONArray avoids cast :-)
// ...
}
See:
http://www.json.org/javadoc/org/json/JSONObject.html#has%28java.lang.String%29
I'm Workin with Mongo using Jongo, when I do a query I receive a LinkedHashMap as result.
Iterator one = (Iterator) friends.find(query).projection("{_id:0}").as(Object.class);
while (one.hasNext()) {
LinkedHashMap data = new LinkedHashMap();
data = (LinkedHashMap) one.next();
String content = data.toString();
}
the problem is that if the json is {"user":"something"} content will be {user=something}, it is not a json is only toString method from HashMap.
How I can get the original JSON?
I don't have a class to map the response and it isn't a solution create a map class, that is why I use a Object.class.
If you have access to some JSON library, it seems like that's the way to go.
If using org.json library, use public JSONObject(java.util.Map map):
String jsonString = new JSONObject(data).toString()
If Gson, use the gson.toJson() method mentioned by #hellboy:
String jsonString = new Gson().toJson(data, Map.class);
You can use Gson library from Google to convert any object to JSON. Here is an example to convert LinkedHashMap to json -
Gson gson = new Gson();
String json = gson.toJson(map,LinkedHashMap.class);
One of the com.mongodb.BasicDBObject constructors takes a Map as input. Then you just have to call the toString() on the BasicDBObject object.
Iterator one = (Iterator) friends.find(query).projection("{_id:0}").as(Object.class);
while (one.hasNext()) {
LinkedHashMap data= new LinkedHashMap();
data= (LinkedHashMap) one.next();
com.mongodb.BasicDBObject bdo = new com.mongodb.BasicDBObject(data);
String json = bdo.toString();
}
I resolved the problem using the following code:
Iterator one = (Iterator) friends.find(query).projection("{_id:0}").as(Object.class);
while (one.hasNext()) {
Map data= new HashMap();
data= (HashMap) one.next();
JSONObject d = new JSONObject();
d.putAll(data);
String content=d.toString();
}
if(data instanceof LinkedHashMap){
json=new Gson.toJson(data,Map.class).toString();
}
else{
json=data.toString();
}
return Document.parse(json);