In this tutorial, we will learn how to parse different types of JSON and concepts regarding JSON such as JSONObject, JSONArray e.t.c.
{ "schema": "http://json.org/example", "title": "Product", "description": "A product from catalog", "type": "object", "properties": { "id": { "description": "The unique identifier for a product", "type": "integer" }, "name": { "description": "Name of the product", "type": "string" } }, "required": ["id", "name"] }
First of all we will learn how to verify that whether the node is a JSONObject or a JSONArray
JSONArray:
[ – represents that it is a json array node.
JSONObject:
{ – represents that it is a json object node.
Here is the method to parse json and get values inside above json:
//suppose we have above JSON in jsonString public void parseJson(String jsonString) throws JSONException{ //getting whole object in obj1 from jsonString //{ //"schema":... // .... // .... //....,"name"] //} JSONObject obj1=new JSONObject(jsonString); //Getting String values inside JSONObject obj1 : //String value with key - schema String schema=obj1.getString("schema"); //String value with key - title String title=obj1.getString("title"); //String value with key - description String description=obj1.getString("description"); //String value with key - type String type=obj1.getString("type"); System.out.println("Schema : "+schema+" Title : "+title+" Description : "+description+" Type : "+type); // JSONObject values inside obj1 with key - properties JSONObject obj2=obj1.getJSONObject("properties"); // JSONObject values inside obj2 with key - id JSONObject obj3=obj2.getJSONObject("id"); //String value inside obj3 with key - description String description2=obj3.getString("description"); //String value inside obj3 with key - type String type2=obj3.getString("type"); System.out.println("Description of JSONObject with key- id : "+description2+" Type of JSONObject with key- id : "+type2); // JSONObject values inside obj2 with key - name JSONObject obj4=obj2.getJSONObject("name"); //String value inside obj4 with key - description String description3=obj4.getString("description"); //String value inside obj4 with key - type String type3=obj4.getString("type"); System.out.println("Description of JSONObject with key- name : "+description3+" Type of JSONObject with key- name : "+type3); //JSONArray value inside obj1 with key - required JSONArray array=obj1.getJSONArray("required"); //String values inside JSONArray array for(int i=0;i<array.length();i++){ System.out.println(array.getString(i)); } }
Let’s take another example:
{ "name": "Cake", "batters": { "batter": [ { "id": "1001", "type": "Regular" }, { "id": "1002", "type": "Chocolate" }, { "id": "1003", "type": "Blueberry" }, { "id": "1004", "type": "Devil's Food" } ] }, "topping": [ { "id": 5001, "type": "None" }, { "id": 5002, "type": "Glazed" }, { "id": 5005, "type": "Sugar" }, { "id": 5007, "type": "Powdered Sugar" }, { "id": 5006, "type": "Chocolate with Sprinkles" }, { "id": 5003, "type": "Chocolate" }, { "id": 5004, "type": "Maple" } ] }
Below is the method to parse above JSON:
public void parseJson2(String jsonString2) throws JSONException{ JSONObject obj=new JSONObject(jsonString2); String name=obj.getString("name"); System.out.println("Name is: "+name); JSONObject obj2=obj.getJSONObject("batters"); //Here we get json array inside obj2 with key- batter JSONArray array=obj2.getJSONArray("batter"); //Getting json objects inside array for(int i=0;i<array.length();i++){ JSONObject obj3=array.getJSONObject(i); //Getting id and type of json objects inside array System.out.println("Id of obj3 : "+obj3.getString("id")+" Type of obj3 : "+obj3.getString("type")); } //Here we get json array inside obj1 with key- topping JSONArray array2=obj.getJSONArray("topping"); //Getting json objects inside array for(int i=0;i<array2.length();i++){ JSONObject obj4=array2.getJSONObject(i); //Getting id and type of json objects inside array2 System.out.println("Id of obj4 at index "+i+" is : "+obj4.getInt("id")+" Type of obj4 at index "+i+" is : "+obj4.getString("type")); } }
Moving to another example where we have 100 json objects with same attributes. Here we would not want to get attributes inside every json object by writing same code again and again, so to do that, we will follow a simpler and efficient way:
Note* : This way can also be used when we do not know the key name whose attributes we want to retrieve.
{ "batchcomplete": "abc", "query": { "pages": { "1": { "pageid": 280636, "title": "Gary Moore" }, "2": { "pageid": 280645, "title": "Tim" }, "3": { "pageid": 280624, "title": "John" }, "4": { "pageid": 280607, "title": "Mary" }, "5": { "pageid": 280626, "title": "Sam" }, . . . "100": { "pageid": 280658, "title": "Mitchell" } } } }
Below is the method to get values from above json:
public void parseJson3(String jsonString3) throws JSONException{ JSONObject obj=new JSONObject(jsonString3); String batchcomplete=obj.getString("batchcomplete"); System.out.println("Batchcomplete : "+batchcomplete); JSONObject obj2=obj.getJSONObject("query"); JSONObject obj3=obj2.getJSONObject("pages"); JSONObject obj4=null; //Getting all the keys inside json object with key- pages Iterator<String> keys= obj3.keys(); while (keys.hasNext()) { String keyValue = (String)keys.next(); obj4 = obj3.getJSONObject(keyValue); //getting string values with keys- pageid and title String pageid = obj4.getString("pageid"); String title = obj4.getString("title"); System.out.println("Page id : "+pageid+" Title : "+title); } }
Note*: To avoid exceptions you should use below function if you want to check whether a JSONObject or JSONArray exists in the json whose key you are specifying in your code.
jsonobject.has("KEY_NAME");//returns true or false
In case of any queries, please feel free to comment.
Please subscribe to get notified about latest posts and updates.
Simple and to the point!
Great stuff, thanks for the explanation 🙂
LikeLike
Glad to help..:)
LikeLike
What libs do you use for this?
LikeLike
I have not used any libraries for this, this is simple json parsing.
LikeLike
Thanks for this tutorial..
i’m having trouble with solving some problems that are occuring when extracting values (leaves) from JSON. with JSONPath i am getting nowhere so i am now looking for a Java solution (i am new to Java).
in your last example i would like to know how to also extract the pagenumbers, so from 1 to 5. i have a simmilar JSON so if you can tell me in your own example i could try and implement it in my JSON file…
thank you in advance and please keep in mind i am new to Java
NOTE: for more info about my specific problem you could take a look here: http://stackoverflow.com/questions/40021828/extract-specific-values-surrounded-by-quotation-marks-using-java
LikeLike
I saw your question on stackoverflow, here is the solution below, i hope it works correctly as i have not checked it, please let me know if you have any questions:
String jsonString=”YOUR JSON STRING”;
JSONObject mainObject=new JSONObject(jsonString);
Iterator keys= mainObject.keys();
while (keys.hasNext())
{
String keyValue = (String)keys.next();
JSONObject obj1 = mainObject.getJSONObject(keyValue);
JSONObject estimatedObj = obj1.getJSONObject(“estimated”);
JSONObject completedObj = obj1.getJSONObject(“completed”);
System.out.print(keyvalue+”-“+estimatedObj.getString(“text”)+”-“+completedObj.getString(“text”));
System.out.println();
}
LikeLike
Hi, would it be possible to show me how you parsed the JSON into “jsonString”
LikeLike
Hello Aakash,
if you could help me find a solution for the below JSON parsing code that would be a great help
I have the following JSON text that I need to parse and sort the items by their name { “Items” : [ { “Name” : “Red Watch”, “Id” : “asdfhd882”, “Model” : “44-1A”, “Stock” : 7 }, { “Name” : “Blue Watch”, “Id” : “asd882”, “Model” : “44-1B”, “Stock” : 2 } ] }
LikeLike
First of all, apologies for a bit late reply. The answer to your question goes like this:
/*jsonString ——- { “Items” : [ { “Name” : “Red Watch”, “Id” : “asdfhd882”, “Model” : “44-1A”, “Stock” : 7 },
{ “Name” : “Blue Watch”, “Id” : “asd882”, “Model” : “44-1B”, “Stock” : 2 } ] }*/
JSONObject mainObject = new JSONObject(jsonString);
JSONArray itemsArray = mainObject.getJSONArray(“Items”);
for(int i = 0; i < itemsArray.length() ; i++){
JSONObject jsonObject = itemsArray.getJSONObject(i);
String name = jsonObject.getString("Name");
String id = jsonObject.getString("ID");
String model = jsonObject.getString("Model");
String stock = jsonObject.getString("Stock");
System.out.println("Name: " + name + " Id: " + id + " Model: " + model + " Stock: " + stock);
}
Hope this helps, let me know if you need help.
LikeLike
From where did you learn JSON?
Also how did you made wordpress blog online? It cost money right?
LikeLike
Great tutorial!
Please could you help me with this question: https://stackoverflow.com/questions/49711566/merge-values-of-two-json-array-into-a-jsonobject-java/49711860#49711860
LikeLike