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

Time:08-11

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;
        
        

CodePudding user response:

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

CodePudding user response:

I'd suggest first starting with mapping out your JSON object to a Java class. So this JSON would convert to something like:

public class JsonObject {
  String cover;
  List<Address> addresses;
}

public class Address {
  String id;
  String NickName;
  String ContactName;
  String Company;
  String City;
  String Country;
  String Type;
}
... plus your getters and setters

You'll notice that the address field is a list to start because that's how the JSON is constructed. Then start by mapping the JSON to this JsonObject class with a JSON library like Jackson. If you use Maven you could add this to your pom:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.3</version>
</dependency>

To map JSON to an object:

ObjectMapper objectMapper = new ObjectMapper();
JsonObject jsonObject = objectMapper.readValue(jsonString, JsonObject.class);

That should map your JSON to the correct object and in that object will be a list of addresses. From there you can create a map and either create a new object or add a Map<String, Address> field to the JsonObject class above.

List to Map example:

Map<String, Address> addressMap = jsonObject.addresses.stream()
.collect(Collectors.toMap(Address::getId, x -> x));
  • Related