Parsing multiple json objects in java - java

I have this json file that I'm trying to parse in my program.
{
"items": [{
"0": {
"item_name":"Test Item",
"item_rarity":2,
"item_material":"STICK",
"required_level":1,
"min_damage":100.0,
"max_damage":200.0,
"item_set":"The cool kids",
"attributes":[{"name":"lifesteal","modifier":20}]
},
"1": {
"item_name":"Test Item",
"item_rarity":2,
"item_material":"STICK",
"required_level":1,
"min_damage":100.0,
"max_damage":200.0,
"item_set":"The cool kids",
"attributes":[{"name":"lifesteal","modifier":20}]
}
}]
}
I am printing the JSON string, but instead of getting the individual objects (0, then 1, then 2, etc...) it only gets the whole array every time I print it out.
Object obj = jsonParser.parse(new FileReader(new File(ValaCraft.getInstance().getDataFolder() + "/test.json")));
JSONObject jsonObject = (JSONObject) obj;
JSONArray items = (JSONArray) jsonObject.get("items");
for (int i = 0; i < items.size(); i++) {
JSONObject item = (JSONObject) items.get(i);
System.out.print(item.toString());
}
Anybody have an idea on how to parse this file (without GSON, attributes is a custom class and I found it complicated to use the auto parse that gson comes with).

What did you find troubling with GSON?
If you pass it to the gson.fromJSON as a JSONObject class, it should work, and you'll be able to get data from the JSON object.
Gson gson = new Gson();
JsonObject jsonFile = gson.fromJson(file.json, JsonObject.class);
Then you can call
JsonArray array = jsonFile.get("items").getAsJsonArray();
Then to grab the attributes from the first element of the array.
array.get(0).getAsJsonObject().get("attributes").getAsJsonArray();

Related

Null pointer observed while trying to fetch the object value from JSON array

I'm trying to loop the calls: JSON array and trying to fetch the machine details JSON object which is present under calls JSON array list as like below:
{
"<dynamicValue>":{
"type":"CORR-ID",
"tags":[
{
"name":"9VB6454145983212H",
"flags":[
"FLAG_DYNAMIC_VALUE",
"FLAG_ID_LOOKUP_SUPPORTED"
]
}
],
"callSummary":[
{
"colo":"lvs",
"pool":"amazon_paymentsplatformserv",
"machine":"stage2utb29958"
},
{
"colo":"lvs",
"pool":"amazon_elmoserv",
"machine":"msmamoserv_0"
},
{
"colo":"lvs",
"pool":"amazon_xopaymentgatewayserv",
"machine":"msmastmentgatewayserv_1"
},
{
"colo":"lvs",
"pool":"amazon_paymentapiplatserv",
"machine":"msmaentapiplatserv_2"
},
{
"colo":"lvs",
"pool":"amazon_userlifecycleserv_ca",
"machine":"stage2utb91581"
},
{
"colo":"lvs",
"pool":"amazon_dafproxyserv",
"machine":"msmasfproxyserv_1"
},
{
"colo":"lvs",
"pool":"paymentserv",
"machine":"te-alm-15757_paymentexecutionserv_0",
"calls":[
{
"colo":"lvs",
"pool":"fimanagementserv_ca",
"machine":"msmgementserv_ca_20"
},
{
"colo":"lvs",
"pool":"fimanagementserv_ca",
"machine":"msmasgementserv_ca_4"
}
]
}
]
}
}
The above JSON file which I stored in String variable and trying to fetch the machine details which is under calls: JSON ARRAY by using below code.
Code:
public static void getHttpUrlformachineList(String response, String CalId, String componentName)
throws Exception
{
//System.out.println(response);
Map<String, String> data = new HashMap<String, String>();
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(response);
JSONObject getValue = (JSONObject) object.get(CalId.trim()); //CalId is the dynamic value that mentioned in the JSON input file
JSONObject getCalSummary = (JSONObject) object.get("callSummary");
JSONArray arrays=(JSONArray) getCalSummary.get("calls");
System.out.println(arrays.size()); // return null pointer
}
Error:
java.lang.NullPointerException: null
at com.online.amazon.hadoop.cal.swagger.utils.Utils.getHttpUrlformachineList(Utils.java:112) ~[classes/:na]
If you notice that calls Array List will not be available in all the callSummary JSON Array, and It will be dynamic and can be available under any component that listed above.
So I just want to dynamically get the calls: JSON array and iterate and fetch machine details.
Can someone help me to achieve this?
Note: I'm using JSON-Simple library to parse and iterate the JSON. It would be great if I get solution on the same.
Updated:
I also tried to create callSummary as JSON array and loop that array to get each JSON object and tried to find the calls but this is also leads to Null pointer.
Also the calls json array is not index specific. It can be anywhere in the payload. It may or may not be there in the payload. I just need to handle if it's exist in any of the component then I need to fetch that machine details
change
JSONArray arrays=(JSONArray) getCalSummary.get("calls");
to
JSONArray arrays= getCalSummary.getJSONArray("calls")
and all other functions where you get objects instead of "get" you should use "getJSONObject", "getString" etc.. then you dont have to cast,
also im pretty sure its not arrays.size() its arrays.length() if you are using package org.json.JSONArray but since key "calls" doesnt exist in every "callSummary" you should check if its null or not before.
You should match the types as specified in your JSON string:
public static void getHttpUrlformachineList(String response, String CalId, String componentName)
throws Exception
{
//System.out.println(response);
Map<String, String> data = new HashMap<String, String>();
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(response);
JSONObject getValue = (JSONObject) object.get(CalId.trim()); //CalId is the dynamic value that mentioned in the JSON input file
JSONArray getCalSummary = (JSONArray) object.get("callSummary"); // callSummary is a JSONArray, not JSONObject
for (int i = 0; i < getCalSummary.length(); i++) {
JSONObject obj = getCalSummary.getJSONObject(i);
if (obj.has("calls")) {
// grab calls array:
JSONArray callsArray = obj.getJSONArray("calls");
}
}
}
Here, you should also check your JSON values with .has(...) method to avoid getting JSONException if a field doesn't exists in your JSONObject.

How to access JSON value?

Very new to JSON, this is probably very simple but I'm not sure how to access the "coordinates" in this JSON I know how to go from resourceSets to resources but get stuck at "point":
{
"resourceSets":[
{
"estimatedTotal":1,
"resources":[
{
"__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
"bbox":[
51.3223903,
-0.2634519,
51.3246386,
-0.2598541
],
"name":"name",
"point":{
"type":"Point",
"coordinates":[
51.3235145,
-0.261653
]
}
}
]
}
]
}
My code so far:
JSONParser parser = new JSONParser();
JSONObject jObj = (JSONObject)parser.parse(result);
JSONArray jsonArray = (JSONArray)jObj.get("resourceSets");
for (int i = 0; i < jsonArray.size(); i ++) {
JSONObject jObjResourceSets = (JSONObject)jsonArray.get(i);
JSONArray jsonArray2 = (JSONArray)jObjResourceSets.get("resources");
System.out.println("Coords" + jObjResourceSets.get("point"));
}
Lets analyse what you're doing (and need to be doing), step by step, in order to get the "coordinates".
First of all, JSON is a great language to transfer static data. It works like a dictionary, where you have a key and the respective value. The key should always be a String, but the value can be a String, an int/double or even an array of other JSON objects. That's what you have.
For instance, "estimatedTotal" is an element (JSONObject) from the "resourceSet" array (JSONArray).
JSONArray jsonArray = (JSONArray)jObj.get("resourceSets");
What you're saying here is straight forward: from your overall JSONObject - jObj - you want to extract the array with key "resourceSets".
Now you have direct access to "resourceSets" array elements: "estimatedTotal", "resources", etc. So, by applying the same logic, in order to access "coordinates" we need to access the "resources" array. And by that I mean to create a JSONArray object like we did before.
JSONArray jsonResourcesArray = (JSONArray)jObjResourceSets.get("resources");
I hope it's clear what's the content of jsonResourcesArray here. It's the JSON array of "__type", "bbox", "name", "point", (...). The Coordinates howevere are inside "point" JSON object. How do we access it?
JSONObject jsonPointObject = (JSONObject) jsonResourcesArray.get("point");
And you know by know that "jsonPointObject" has as its values the following JSON objects: "type" and "coordinates". Coordinates is an array of values, so do we have to use JSONArray or JSONObject?
JSONArray jsonCoordinatesArray = (JSONArray) jsonPointObject.get("coordinates");
From which we mean: from the jsonPointObject we want to extract the array that has key "coordinates". Now your array is a JSONArray with values of jsonCoordinatesArray.get(0) and jsonCoordinatesArray.get(0).
Now you have, not only the code to get those values, but the understanding of how JSON works and how Java interacts with it so you can solve any Json problem from now on.
Normally this code works for the given JSON object. However I'll put the tested formatted JSON value below the java code so you can test it as well.
Note that this code will get you all the coordinates of all the elements in your object.
public static void main(String[] args) throws Exception {
String result = getJsonString();
// Getting root object
JSONParser parser = new JSONParser();
JSONObject jObj = (JSONObject)parser.parse(result);
// Getting resourceSets Array
JSONArray jsonArray = (JSONArray)jObj.get("resourceSets");
for (int i = 0; i < jsonArray.size(); i++) {
// Getting the i object of resourceSet
JSONObject jObjResourceSets = (JSONObject) jsonArray.get(i);
// Getting resources list of the current element
JSONArray jsonArray2 = (JSONArray) jObjResourceSets.get("resources");
for (int j = 0; j < jsonArray2.size(); j++) {
// Getting the j resource of the resources array
JSONObject resource = (JSONObject) jsonArray2.get(j);
// Getting the point object of the current resource
JSONObject point = (JSONObject) resource.get("point");
// Getting the coordinates list of the point
JSONArray coordinates = (JSONArray) point.get("coordinates");
for (int k = 0; k < coordinates.size(); k++) {
System.out.println("Coordinates[" + k + "]: " + coordinates.get(k));
}
// Printing an empty line between each object's coordinates
System.out.println();
}
}
}
The tested JSON Object:
{
"resourceSets":[
{
"estimatedTotal":1,
"resources":[
{
"__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
"bbox":[
51.3223903,
-0.2634519,
51.3246386,
-0.2598541
],
"name":"name",
"point":{
"type":"Point",
"coordinates":[
51.3235145,
-0.261653
]
}
}
]
}
]
}
If it worked please mark it as the answer.
Good luck ^^
B.
You need the following piece of code to get the data.
JSONArray jsonArray2 = (JSONArray)jObjResourceSets.get("resources");
/**
* here we should note that the "resources" is only having one JSON object hence we can take it as below
* from 0th index using ((JSONObject)jsonArray2.get(0)) these piece of code and the next part is to take the point JSONObject
* from the object.
*/
JSONObject temp = (JSONObject)((JSONObject)jsonArray2.get(0)).get("point");
System.out.println("Coords"+temp.get("coordinates")); //this will give you the coordinates array
//now if you want to do further processing, traverse in the jsonArray like below
JSONArray arr= (JSONArray)temp.get("coordinates");
System.out.println("X coordinate:"+arr.get(0));
System.out.println("Y coordinate:"+arr.get(1));
For more information and further details on JSONObject and JSONArray you can go through this linkparsing-jsonarray-and-jsonobject-in-java-using-json-simple-jar
json-simple-example-read-and-write-json

Value as string array in gson key value

I'm new to JSON. I'm trying to assign value (in key value pairs) as array of strings using GSON.
The JSON should look like as below:
{ "name": "path", "value": [ "/my-path" ,"/my-path2","/newpath"] }
How can I achieve this?
Thanks.
Even thoe I will hardly recommend you to use POJOS, gson is flexible enough to allow you to do what you want:
JsonObject jo = new JsonObject();
jo.addProperty("name", "path");
JsonArray jsonArray = new JsonArray();
jsonArray.add("my-path");
jsonArray.add("my-path2");
jsonArray.add("my-new-path");
jo.add("value", jsonArray);
System.out.println(jo);

Parse Json array without keys

I want to parse an array from Server but I can't obtain the array
Here is the jsonString Successfully got :
{
"status":"OK",
"message":"this is your start and end coordinates",
"data":"{\"start\":[\"35.778763\",\"51.427360\"],\"end\":[\"35.768779, 51.415002\"]}"
}
I want the Double Values from data arraylist:
//try/catch
Log.d(TAG, "Passes here");
JSONObject jObject = new JSONObject(jsonString);
JSONArray jData = jObject.getJSONArray("data");
Log.d(TAG, "Not PAASING HERE !!! ");
JSONArray jArrayStart = (JSONArray) jData.get(0);
JSONArray jArrayEnd = (JSONArray) jData.get(1);
latitudeStart = (Double) jArrayStart.get(0);
longtitudeStart = (Double) jArrayEnd.get(1);
latitudeEnd = (Double) jArrayEnd.get(0);
longtitudeEnd = (Double) jArrayEnd.get(1);
What you're trying to parse, is a string.
{
"status": "OK",
"message": "this is your start and end coordinates",
"data": "{\"start\":[\"35.778763\",\"51.427360\"],\"end\":[\"35.768779, 51.415002\"]}"
}
So it works like this:
//first, retrieve the data from the response JSON Object from the server
JSONObject response = new JSONObject(jsonString);
String status = response.getString("status");
String message = response.getString("message");
//Note this: "data" is a string as well, but we'll have to parse that later.
String data = response.getString("data");
//get the doubles from the arrays from the "data" component.
JSONObject dataObject = new JSONObject(data);
JSONArray start = dataObject.getJSONArray("start");
JSONArray end = dataObject.getJSONArray("end");
for (int i = 0; i < start.length(); i++) {
String value = start.getString(i);
//do something with the start String (parse to double first)
}
for (int i = 0; i < end.length(); i++) {
String value = end.getString(i);
//do something with end String (parse to double first)
}
So data is actually a String, but represents a JSONObject (which you'll have to parse), which, in its turn, contains two JSONArrays.
If data was a JSONObject instead of a String, the JSON would have looked like this:
{
"status": "OK",
"message": "this is your start and end coordinates",
"data": {
"start": [
"35.778763",
"51.427360"
],
"end": [
"35.768779", //note that in your example, this quote is missing (first quote on next line too)
"51.415002"
]
}
}
The value of data is not a JSONArray its JSONObject
Explanation
JSONObject will be surrounded by {}
JSONArray will be surrounded by []
data is not an array, it is a json object and therefore you can not access it the way you are doing.
If you want to fetch start array from json object "data" then use below
jObject.optJSONObject("data").optJSONArray("start");
same thing can be used to retrieve "end" json array.
then use optJSONObject() and/or optString() API to retrieve required value from json array.

simpleJson parsing in Java

I'm very new to parsing JSON. I have looked all over and cannot seem to grasp the idea to my particular problem. I'm having a hard time understanding how to get a JSON object from a JSON array. My example is below
[{"styleId":94,
"status":"verified",
"abv":"4.2",
"name":"Bud Light"}]
Here is my current code
JSONParser parser = new JSONParser();
Object obj = parser.parse(inputLine);
JSONObject jsonObject = (JSONObject) obj;
Long currPage = (Long)jsonObject.get("currentPage");
System.out.println(currPage);
JSONArray jArray = (JSONArray)jsonObject.get("data");
System.out.println(jArray);
inputLine is my orignal JSON. I have pulled a JSONArray out of the original JSONObject that has the "data" tag. Now this is where I'm stuck and given the JSONArray at the top. Not sure how to iterate through the Array to grab JUST the "name" tag.
Thanks for the help in advanced!
To iterate in a JSONArray you need to go through each element in a loop.
int resultSize = jArray.length();
JSONObject result;
for (int i = 0; i < resultSize; i++) {
result = resultsArray.getJSONObject(i);
String name = result.getString("name");
// do whatever you want to do now...
}
just use Gson . it works well out of the box with any object type you supply.
This is an example from the user's guide:
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);

Categories

Resources