0

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;
        
        

1 Answers1

0

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"}
Raymond Choi
  • 1,065
  • 2
  • 7
  • 8
  • so if I just want the country type what I should do is that JSONObject jsonName = (JSONObject) o; String name = (String)jsonName.get("Country");? – roger xiang Aug 11 '22 at 02:02
  • Continue my coding above where JSONObject address is defined... String name = (String) address.get("Country"); – Raymond Choi Aug 11 '22 at 02:16
  • So if I want to get the city is this look good ? public String getCity(int id) { JSONObject add = null; for(Object find : address){ if(((JSONObject)find).get("id").equals(id)){ add = (JSONObject) find; } } city = (String)add.get("City"); return city; } – roger xiang Aug 11 '22 at 14:51
  • Good, and practice more. Enjoy programming! – Raymond Choi Aug 11 '22 at 15:03