javajsonjson-arrayagg

I want to extract the value from JSON by same id one id using java


So the json look like this

{
"cover":"AddressBook",
"Addresses":[
    {
        "id":"1",
        "NickName":"Rahul",
        "ContactName":"Dravid",
        "Company":"Cricket",
        "City":"Indore",
        "Country":"India",
        "Type":"Address"
     },
    {
        "id":"2",
        "NickName":"Sachin",
        "ContactName":"Tendulkar",
        "Company":"Cricket",
        "City":"Mumbai",
        "Country":"India",
        "Type":"Address"
     }
]

}

I want to extract the data from the id = 1 using the JSON array, but I am not sure how to use the syntax or some other way the code I have is this :

        JSONParser jsonParser = new JSONParser();
        FileReader reader = new FileReader("AddressBook.json");
        Object obj = jsonParser.parse(reader);
        address = (JSONArray)obj;
        
        

Solution

  • You have to loop through the "Addresses" array.

    JSONObject addressBook = (JSONObject) jsonParser.parse(reader);
    JSONArray addresses = (JSONArray) addressBook.get("Addresses");
    JSONObject address = null;
    for (Object find : addresses) {
        if (((JSONObject) find).get("id").equals("1")) {
            address = (JSONObject) find;
        }
    }
    System.out.println(address.toJSONString());
    

    Output

    {"Company":"Cricket","Type":"Address","Country":"India","id":"1","City":"Indore","NickName":"Rahul","ContactName":"Dravid"}