JSON how to access entries within entries? - java

Consider this:
Dogs {
001{
age{
5
}
}
002{...}
...
}
I'd like to ultimately find the age of a dog, however, I do not know how many ids there are, and which is going to be the parameter.
So how exactly can I read this JSON?
I assume it would look something like this jsonObj.dogs.(desiredDog.getID()).age, yet getID would yield either an integer or a string, and I don't know if Java would understand I'm trying to conjure up a key.

I am assuming you're using org.json.simple. All you need to do is iterate over the keys of Dog objects, obtain them and then extract their age.
JSONParser parser = new JSONParser();
JSONObject rootObj = (JSONObject) parser.parse(yourJson);
for(Object key : rootObj.keySet()){
JSONObject dog = (JSONObject) object.get(key);
int age = (int) dog.get("age");
}

Related

Iterate JSON and get fields from JSON

I've tried different solutions but I'm not able to iterate through this JSON and/or get direct specific values.
Could any one help on:
Iterating through all the fields sequentially.
Getting direct access to some fields (eg. when getting this response, access directly to "packet-count" where its value equals 3281).
{"flow-node-inventory:flow":[{"id":"42","priority":10,"table_id":0,"opendaylight-flow-statistics:flow-statistics":{"packet-count":3281,"byte-count":317738,"duration":{"nanosecond":252000000,"second":3432}},"idle-timeout":10000,"cookie":31,"instructions":{"instruction":[{"order":0,"apply-actions":{"action":[{"order":0,"output-action":{"output-node-connector":"1","max-length":0}}]}}]},"match":{"ethernet-match":{"ethernet-source":{"address":"00:00:00:00:00:02"},"ethernet-destination":{"address":"00:00:00:00:00:01"}}},"hard-timeout":50000,"flags":""}]}
I tried to use org.json but any other library would be okay.
You will have to check the structure of your JSON Object and create a structure for the entities you encounter accordingly. For instance, the first thing in your JSON object is an array, so this is the first thing you should care about. Imagine it as a continuous encapsulation. Check the code below for more information.
JSONObject jobj = new JSONObject(stringJson);
JSONArray flowNodeInv = jobj.getJSONArray("flow-node-inventory:flow");
for (int i = 0; i < flowNodeInv.length(); i++){
JSONObject segment = (JSONObject) flowNodeInv.get(i);
JSONObject stats = segment.getJSONObject("opendaylight-flow-statistics:flow-statistics");
int number = stats.getInt("packet-count");
System.out.println("packet-count: "+ number);}
Try This
jObject = new JSONObject(contents.trim());
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( jObject.get(key) instanceof JSONObject ) {
}
}
To get direct access to the fields you can create a Java Object from the JSON String using an ObjectMappet (com.fasterxml.jackson). For example:
ObjectMapper mapper = new ObjectMapper();
MyClass myClass = mapper.readValue(jsonString, MyClass.class);

Iterating the JSON object using Java not working exactly

I'm trying to get one JSON object and iterate it. In this case it should iterate only once because I'm having only one complete JSON object, if it has multiple, it should iterate multiple times. But rather it shows the system.out.println string twice. I don't understand whats wrong in this code?
String str = "{\"userId\":\"1234\",\"businessPrimaryInfo\":{\"53bd2a4\":{\"businessSpecificInfo\":{\"businessType\":\"Manufacturing\",\"tradingPlace\":\"Hyderabad\"}},\"53bd2a4e\":{\"businessSpecificInfo\":{\"businessType\":\"Milling\",\"tradingPlace\":\"Mumbai\"}}}}";
JSONObject jsonObj = new JSONObject(str);
Iterator<String> keys = jsonObj.keys();
// Iterate all the users.
while (keys.hasNext()) {
String key = keys.next();
try {
// If the user has Business primary info as JSON object.
if (jsonObj.has("businessPrimaryInfo")) {
JSONObject jsonBizPrimaryInfo = jsonObj
.getJSONObject("businessPrimaryInfo");
System.out.println("Object is:" + jsonBizPrimaryInfo);
}
} finally {
}
}
Please have a look and let me know where I'm doing wrong.
The two keys that are causing your loop to iterate twice are: userId and businessPrimaryInfo. But you ask the main JSON object if it has a businessPrimaryInfo key. Which it has for every iteration.
What you need to do is check that the current key is businessPrimaryInfo.
Or, you can just ask the primary object if it has a businessPrimaryInfo key, and if so, ask for that child object.

Json can work with sets

My question is how JSON works with serializing Sets because in my example , "propertyItems.getAddress().getCity().getProvinces().getCities()" is set of cities (Set) , i am iterating on it through for-each loop and putting it into json array. However it contains two cities i.e. MONTREAL and QuebecCity. But my url is only showing me "MONTREAL". Why its so? Json can't serialize sets provided to it?
JSONArray jarray = new JSONArray();
try {
JSONObject obj = new JSONObject();
for(Cities city:propertyItems.getAddress().getCity().getProvinces().getCities()){
obj.put("City Name",city.getCityname());
}
jarray.put(obj);
catch (JSONException e) {
logger.error(Constants.METHOD_INSIDE_MESSAGE +"getAuthors",e);
}
return jarray.toString();
}
** URL Output:** City Name :Montreal
The JSON specification states
The names within an object SHOULD be unique.
In the JSON parser/generator implementation you are using, ie. JSONObject, it seems the keys are unique. Every time you put an object with the same key, it overwrites the one added before it. Regardless of how many you put, the JSONObject will only contain one entry.

create json object from other json objects

I have two json objects -- not strings, please -- that I want to combine into one json object as shown below.
The two objects:
JSONObject pen = {"plastic":"blue"}
JSONObject book = {"Maya":"Bird"}
Desired result:
JSONObject bag = {"plastic":"blue","Maya":"Bird"}
Is there an elegant way to do this? I mean without extracting the values of each pen and book and then re-insert them into bag using something like
bag.put("plastic","blue");
I am using org.codehaus.jettison.json.JSONObject if that information is necessary.
Naively, it seems like you could just do something like:
Iterator it = pen.keys();
while(it.hasNext())
{
String k = it.next();
bag.put(k, pen.getJSONObject(k));
}
// bag now has the combined key,value pairs.
But it has its obvious limitations.

Logical solution for creating a JSON structure

I am not sure if it possible or not but I think it can be done using JSONArray.put method.
Heres my problem:
I have got two lists:
ArrayList<Students> nativeStudents;
ArrayList<transferStudents> transferStudents = nativeStudents.getTransferStudentsList();
The JSON that I generate with transferStudents list is right here: http://jsfiddle.net/QLh77/2/ using the following code:
public static JSONObject getMyJSONObject( List<?> list )
{
JSONObject json = new JSONObject();
JsonConfig config = new JsonConfig();
config.addIgnoreFieldAnnotation( MyAppJsonIgnore.class );
if( list.size() > 0 )
{
JSONArray array = JSONArray.fromObject( list, config );
json.put( "students", array );
}
else
{
//Empty Array
JSONArray array = new JSONArray();
json.put( "students",
array );
}
return json;
}
Now what I want to get is JSON data with following structure: http://jsfiddle.net/bsa3k/1/ (Notice the tempRollNumber field in both array elements).
I was thinking of doing: (The if condition here is used for a business logic)
if(transferStudents.getNewStudentDetails().getRollNumber() == nativeStudents.getNativeStudentDetails.getStudentId()){
json.put("tempRollNumber", transferStudents.getNewStudentDetails().getRollNumber());
}
but this would add tempRollNumber outsite the array elements, I want this JSON element to be part of every entry of students array.
PS: I cant edit the transferStudents class in order to add tempRollNumber field.
Since no one has come up with anything better I'll turn my comments above into an answer.
The best way to handle this is to create an object model of your data and not create the JSON output yourself. Your app server or container can handle that for you.
Though you cannot change the objects you receive in the List you can extend the object's class to add your own fields. Those fields would then appear in the JSON when you marshall it.

Categories