Getting NullPointerException while parsing JSONArray - java

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

Related

Find JSON object in JSON array

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.

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

parse and get specific field from HTTP response in java

I try to parse a HTTP response to a JSONObject and retrieve some fields, coould be a String or int.
My response is a json array like this:
[{nid: "24161",changed: 1445936169,created: "1444728767",language: "en",status: 1,title: "bicycle",type: "product",uid: "2172",vid: "24161"}]
And I tried using:
JSONObject myObject = new JSONObject(response);
And gson , still after parsing the response turns to {}.
Thanks for any help.
You must use JSONArray instead of JSONObject
JSONArray array = new JSONArray(response);
You can then iterate throw the array and get the fields you want
for(int i=0; i<array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String nid = object.getString("nid");
int changed = object.getInt("changed");
//...
}
You are parsing json array into object. Use JSONArray instead of JSONObject
JSONArray myArray = new JSONArray(response);
you can get your object by index from your array.

Json Iterating using java

Here is my json Object.
{"id":"mrbbt6f3fa99gld0m6n52osge0",
"name_value_list":
{"user_default_dateformat":{"name":"user_default_dateformat","value":"m/d/Y"}},
"module_name":"Users"}
I got id,and module_name through following code.How can i get user_default_dateformat?.
I know it may so simple but I am a newbie in json.
String jsonResponse;
while ((jsonResponse = br.readLine()) != null) {
jsonOutput = jsonResponse;
}
JSONObject job = new JSONObject(jsonOutput);
System.out.println(job);// i can see the same json object
that i showen above.
sessionID = job.get("id").toString();
Exception generating coge
JSONObject job2=new JSONObject(job);
dateFormat = job2.get("user_default_dateformat").toString();
The Eexception is
org.json.JSONException: JSONObject["user_default_dateformat"] not found.
Thanks,
name_value_list is also an Object.
JSONObject job2 = new JSONObject(job.get("name_value_list"));
So there you get
job2.get("user_default_dateformat");
Every {} in your JSON is an object. So for every String you get which is something like {"xy":"za","ab":"cd"} you have to cast it to the JSONObject
Edit for your error:
As you can see in your code the line:
JSONObject job2=new JSONObject(job);
will try to generate a JSONObject out of your JSONObject.
You have to get the JSONObject in your JSONObject.
You want to get the user_default_dateformat which is in your JSONObject:
String name_value_list_string = job.get("name_value_list").toString();
//this string is another json-string which contains the user_default_dateformat
JSONObject name_value_list_object = new JSONObject(name_value_list_string);
//This JSONObject contains the user_default_dateformat but this is also a JSONObject
String user_default_dateformat_string = name_value_list_object.get("user_default_dateformat").toString();
//this String contains the user_default_dateformat JSONString
JSONObject user_default_dateformat_object = new JSONObject(user_default_dateformat_string);
//This JSONObject contains the String values of your user_default_dateformat
if you are using JSONSimple library you can use this:
jsonObject = (JSONObject) new JSONParser().parse(jsonstr);
System.out.println((JSONObject)jsonObject.get("name_value_list"))).get("user_default_dateformat"));
This should give you the required result.

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