Shubham
Shubham

Reputation: 25

How to access nested elements of JSON data in Java?

I'm getting JSON data from a url and I want to show the data on my website. I am successfully showing all JSON data except JSON Hierarchy (JSON Object) data. I am able to access JSONArray person and error data. But, I am not able to access hierarchy (JSON Object) updated data.

I want to access updated.time.

import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;

public class ParseJson1 {

public static void main(String[] args) {
    String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
    /*
   {
"person": [
    {
        "name": "John",
        "city": "Mumbai"
    },
    {
        "name": "Rahul",
        "city": "Delhi"
    },
    {
        "name": "Sanjana",
        "city": "Amritsar"
    },
    {
        "name": "Anjali",
        "city": "Hyderabad"
    },
    {
        "name": "Mukund",
        "city": "Bangalore"
    },
    {
        "name": "Raunak",
        "city": "Patna"
    }
],
"updated": {
    "time": "14:17:48",
    "date": "2016-04-10"
},
"error": "2353"
}

 */

    try {
        String genreJson = IOUtils.toString(new URL(url));
        JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
        // get the error
        System.out.println(genreJsonObject.get("error"));

        //Get Array Values
        JSONArray genreArray = (JSONArray) genreJsonObject.get("person");
        // get the first genre
        JSONObject firstGenre = (JSONObject) genreArray.get(0);
        System.out.println(firstGenre.get("name"));
        // get the Second
        JSONObject firstGenre = (JSONObject) genreArray.get(1);
        System.out.println(firstGenre.get("name"));
        // get the third
        JSONObject firstGenre = (JSONObject) genreArray.get(2);
        System.out.println(firstGenre.get("city"));


    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }
}
}

Upvotes: 1

Views: 6167

Answers (2)

Arpit Agrawal
Arpit Agrawal

Reputation: 321

Try this

public static String[] getInfo(String url)
{
    String result=//I am assuming your json response is in result
    String[] titles=null;
    try {
        JSONObject jsonObject=new JSONObject(result);
        JSONObject temp=null;
        JSONArray jsonArray=jsonObject.getJSONArray("person");
        int length=jsonArray.length();
        person=new String[length];
        for (int i=0;i<length;i++){
            temp= (JSONObject) jsonArray.get(i);
            titles[i]=temp.getString("name")+temp.getString("city");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return titles;
}

This works fine, if you face any problem write in comments.

Happy coding!!

Upvotes: 0

Vikrant Kashyap
Vikrant Kashyap

Reputation: 6846

This json Result appears what you got from your api URL . Right ??

 {  
   "person":[  
      {  
         "name":"John",
         "city":"Mumbai"
      },
      {  
         "name":"Rahul",
         "city":"Delhi"
      },
      {  
         "name":"Sanjana",
         "city":"Amritsar"
      },
      {  
         "name":"Anjali",
         "city":"Hyderabad"
      },
      {  
         "name":"Mukund",
         "city":"Bangalore"
      },
      {  
         "name":"Raunak",
         "city":"Patna"
      }
   ],
   "updated":{  
      "time":"14:17:48",
      "date":"2016-04-10"
   },
   "error":"2353"
}

Now Here is a Code how to Iterate or parse your json Object. I Suppose that above Result json is stored in a String Variable String genreJson as per Your Code.

Here I wrote a method to solve your Problem. You may take a reference of it and may try your own code.

public void testYourJSON(String genreJson){

    JSONParser parser=new JSONParser();  //parser used to parse String to Correct Json format.

    JSONObject obj_ComplexData = (JSONObject) parser.parse(genreJson); // Now Your String Converted to a JSONObject Type.

     //person tag Array Data is fetched and Stored into a JSONArray Object.
    JSONArray obj_arrayPersonData = (JSONArray) parser.parse(obj_ComplexData.get("person").toString()); 

    for (Object person : obj_arrayPersonData ) { //Iterate through all Person Array.
           System.out.println(person.get("name"));
           System.out.println(person.get("city"));
    }

    //Select "updated" Tag Json Data.
    JSONObject obj_Updated = (JSONObject) parser.parse(obj_ComplexData.get("updated").toString());

    System.out.println(obj_Updated.get("time")); //display time tag.
    System.out.println(obj_Updated.get("date")); //display date tag.


    System.out.println(obj_Updated.get("error")); //display Your Error.

}

Upvotes: 1

Related Questions