Iterate JSON and get fields from JSON - java

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);

Related

JSON how to access entries within entries?

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");
}

How to extract a json object from a json array by name in java?

I'm recieving JSON from the Google Directions API and the request is like the one shown here (under Directions Responses -> Json Output) link
I don't know how to extract a particular entry from within a json array. Basically what I need is the JsonArray equivalent of JSONObject method get(String key) where you can get the entry mapped to a specific key. However, the JSONArray has no such method, and seems to only support the retrieval of info through a specific index. This is all well and good, but the google directions reponses' contents can vary - so I need a way to either find a specific key-value pairing, or loop through the entire array and have a way to check the value of the key. I could even find a way to determine the key that a JSONObject was mapped to. Any suggestions? Ex: How would you extract the distance JSONObject out of the JSONArray legs?
Edit: This is where I am stuck: Refering the the JSON example output here... I am trying to get the value of the "overview_polyline" entry within the "routes" json array. Since I cannot access the "overview_polyline" entry simply by referring to its name, I must loop through the array until I get to that entry. But how would I know when I got to that entry? Yes, perhaps I could check if the JSONObject representation of the entry had a "points" key, but that isn't necessarily exclusive to the "overview_polyline" entry. Also, I cannot simply get the (array.length() - n) entry because the number of entries returned in the array may vary. In short, it seems to me that I need a way to check the name ("overview_polyline") of each JSONObject to reliably be able to extract that information.
JSONArray routesArray = resultObj.getJSONArray("routes");
for(int i = 0; i < routesArray.length(); i++)
{
JSONObject obj = routesArray.optJSONObject(i);
if(obj != null)
{
//How do I determine if this object is the "overview_polyline"
//object?
}
}
The route is a JSONArray of JSONObject, so you have to do it this way:
JSONArray routesArray = resultObj.getJSONArray("routes");
for(int i = 0; i < routesArray.length(); i++) {
JSONObject obj = routesArray.optJSONObject(i);
if(obj != null) {
JSONObject polyline = obj.optJSONObject("overview_polyline");
}
}

Jackson deserialization convertValue vs readValue

I have a org.json.JSONArray that contains JSONObjects and I am trying to map those to a POJO. I know the type of the POJO I want to map to. I have 2 options and I m trying to figure out which is better in performance.
Option 1:
ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.reader().withType(MyPojo.class);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject obj = jsonArr.getJSONObject(i);
MyPojo pojo = reader.readValue(obj.toString());
... other code dealing with pojo...
}
Option 2:
ObjectReader mapper = new ObjectMapper();
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject obj = jsonArr.getJSONObject(i);
MyPojo pojo = mapper.convertvalue(obj, MyPojo.class);
... other code dealing with pojo...
}
For sake of argument, lets assume the length of the JSONArray is 100.
From what I have looked so far from the source code, option 1 seems better since the Deserialization context and the Deserializer is created only once, while in case of option 2, it will be done for each call.
Thoughts?
Thanks!
I will try to explain the difference, with the problem I faced. I used both in a complex conversion I needed to use.
My request was of the format as below.
"{Key=a1, type=ABC}"
I wanted to convert it to some class's (A1) instance.
class A1 {
private String key;
private String type;
}
As is clear, the keys are not strings (i.e. not enclosed in double quotes)
With mapper.readValue
I will get error as below:
com.fasterxml.jackson.core.JsonParseException: Unexpected character ('k' (code 115)): was expecting double-quote to start field name
With mapper.convertValue
I will get an instance of A1 as I required.

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.

JSON parsing to Java - Android application

I need help with parsing json string in Java Android Appl.
Text of JSON file:
{"data":{"columns":["location_id","name","description","latitude","longitude","error","type","type_id","icon_media_id","item_qty","hidden","force_view"],"rows":[[2,"Editor","",43.076014654537,-89.399642451567,25,"Npc",1,0,1,"0","0"],[3,"Dow Recruiter","",43.07550842555,-89.399381822662,25,"Npc",2,0,1,"0","0"] [4,"Protestor","",43.074933,-89.400438,25,"Npc",3,0,1,"0","0"],[5,"State Legislator","",43.074868061524,-89.402136196317,25,"Npc",4,0,1,"0","0"],[6,"Marchers Bascom","",43.075296413877,-89.403374183615,25,"Node",22,0,1,"0","0"] [7,"Mary","",43.074997865584,-89.404967573966,25,"Npc",7,0,1,"0","0"]]},"returnCode":0,"returnCodeDescription":null}
How can get values: location_id, name, latitude, longitude.
Thanks, Michal.
Using manual parsing you can implement it like this:
JSONArray pages = new JSONArray(jsonString);
for (int i = 0; i < pages.length(); ++i) {
JSONObject rec = pages.getJSONObject(i);
JSONObject jsonPage =rec.getJSONObject("page");
String address = jsonPage.getString("url");
String name = jsonPage.getString("name");
String status = jsonPage.getString("status");
}
in your case note that your outer elemnt data is type of JSONObject and then you have a JSONArray
mine json file:
[{"page":{"created_at":"2011-07-04T12:01:00Z","id":1,"name":"Unknown Page","ping_at":"2011-07-04T12:06:00Z","status":"up","updated_at":"2011-07-04T12:01:00Z","url":"http://www.iana.org/domains/example/","user_id":2}},{"page":{"created_at":"2011-07-04T12:01:03Z","id":3,"name":"Down Page","ping_at":"2011-07-04T12:06:03Z","status":"up","updated_at":"2011-07-04T12:01:03Z","url":"http://www.iana.org/domains/example/","user_id":2}}]
note that mine starts from [, which means an array, but yours from { and then you have [ array inside. If you run it with a debugger, you can see exactly what´s inside your json objects.
There are also better approaches like:
Jackson
Jackson-JR (light-weight Jackson)
GSON
All of them can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
First of all, you need to know about Json parsing in android, so for that first read this: JSONObject, in that class, you will see the below methods:
getJSONArray(String name)
getJSONObject(String name)
getString(String name)
and many more methods to be used while implementing JSON parsing in android.
Update:
And if you are still confused then click on below link to have many examples available on web: Android JSON Parsing
You need to use the GSON lib
http://code.google.com/p/google-gson/
Object Examples
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj
If you mean to navigate easily the Json Tree, you can use JSON Path, that is query system, similar to XPath to XML, that you can use to pick some elements in a json tree using text expressions.
http://code.google.com/p/json-path/ That's a good implementation
If you just mean that you want to parse that JSon you can use Gson from google (that is compatible with Android I guess).
This contains a complete example for your case.

Categories