Find JSON object in JSON array - java

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.

Related

Parse JSON file in Java: getJSONObject(int) is undefined

I`m trying to fetch some values fron a JSON file using:
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("C:\\myfile.json"));
JSONArray array= new JSONArray();
array.add(obj);
If I run: System.out.println(array); , the output is
[{"flowrate":{"mod":0,"value":110},"command":{"cancel":0,"start":0}}]
, which is my json file.
My problem is how to get value from a specific field, let's say the value of "comand":"cancel".
I've tried JSONObject myitem = array.getJSONObject(1).getJSONObject("cancel"); with no success (error: getJSONObject(int) is undefined for the type JSONArray).
I mention that I'm using the json-simple toolkit.
I also could not validate your JSON. I made an assumption that you wanted to create an array of two objects (flowrate and command) and fixed the JSON:
String value = "[{\"flowrate\":{\"mod\":0,\"value\":110}},{\"command\":{\"cancel\":0,\"start\":0}}]";
JSONParser parser = new JSONParser();
Object obj = parser.parse(value);
JSONArray array=(JSONArray)obj;
JSONObject jo = (JSONObject) array.get(1);
System.out.println(jo.get("command"));
which gives the following output:
{"cancel":0,"start":0}
Process finished with exit code 0
After many hours of searching, I discovered that there is big difference between { } and [ ], therefore differnent methodes to parse them:
In my case:
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("C:\\myfile.json"));
JSONObject jsonObject = (JSONObject) json;
JSONObject command= (JSONObject) jsonObject.get("command");
System.out.println("command: " + command);
long cancel= (Long) command.get("cancel");
System.out.println("cancel: " + cancel);
Here you'll find the best example for nested json objects

Parser for json Object in java

I am trying to create a common parser in java.I am passing json object from different class based on my need.But parsing doesnot works for me.Can anybody help me to make a JSONObject parser in java.Any help will be highly appreciable....
This is my code for common parser
public JSONObject jsonParser(JSONObject objJson){
//JSONObject myjson = new JSONObject(objJson);
JSONArray the_json_array = objJson.getJSONArray("profiles");
JSONObject SnapshotRequest= objJson.g;
Iterator x = SnapshotRequest.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(songs.get(key));
}
}
In this code I am getting an error that need to cast.
JSONArray the_json_array = objJson.getJSONArray("profiles");
But casting won't work.

remove object from json array based on condition using java

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.

How to have each record of JSON on a separate line?

When I use JSONArray and JSONObject to generate a JSON, whole JSON will be generated in one line. How can I have each record on a separate line?
It generates like this:
[{"key1":"value1","key2":"value2"}]
I need it to be like following:
[{
"key1":"value1",
"key2":"value2"
}]
You can use Pretty Print JSON Output (Jackson).
Bellow are some examples
Convert Object and print its output in JSON format.
User user = new User();
//...set user data
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));
Pretty Print JSON String
String test = "{\"age\":29,\"messages\":[\"msg 1\",\"msg 2\",\"msg 3\"],\"name\":\"myname\"}";
Object json = mapper.readValue(test, Object.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
Reference : http://www.mkyong.com/java/how-to-enable-pretty-print-json-output-jackson/
You may use of the google-gson library for beautifying your JSON string.
You can download the library from here
Sample code :
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJSONString);
String prettyJsonString = gson.toJson(je);
OR
you can use org.json
Sample code :
JSONTokener tokener = new JSONTokener(uglyJsonString); //tokenize the ugly JSON string
JSONObject finalResult = new JSONObject(tokener); // convert it to JSON object
System.out.println(finalResult.toString(4)); // To string method prints it with specified indentation.
Refer answer from this post :
Pretty-Print JSON in Java
The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:
JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4); // stringify with 4 spaces at each level
and please refer this : https://stackoverflow.com/a/2614874/3164682
you can also beautify your string online here.. http://codebeautify.org/jsonviewer
For gettting a easy to read json file you can configure the ObjectMapper to Indent using the following:
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

parsing URL in String from JSON

1) I've got a JSON file:
{
"serverURI":"http://localhost:8080/PocketUNI_API/serverURLs",
"newsURI":"http://localhost:8080/gateway/rss/rss.xml",
"modulesURI":"http://localhost:8080/PocketUNI_API/modules"
}
2) I need to get URLs on Java client in String format.
String json = jsonReceiver.makeHttpRequest(URL_SERVER, "GET", params);
JSONArray uris = new JSONArray(json);
Receiver works fine and json shows the correct string received, but when it goes to parsing with JSONArray it throws an error
org.json.JSONException: Value {"serverURI":"http:\/\/192.168.0.... of type org.json.JSONObject cannot be converted to JSONArray.
Question: How to parse json with URL values?
You don't get a JSONArray but a JSONObject.
JSONObject uris = new JSONObject(json);
json is a json object not an array, that is why you are getting the error. An array will be wrapped with in [ and ], and objects within { and }.
JSONObject uris = new JSONObject (json);
Instead of JSONArray you must use JSONObject.
JSONObject uris = new JSONObject(json);
In your code just replace JSONArray to JSONobject
JSONObject uris = new JSONObject(json);

Categories

Resources