0
   {
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": 10021
    },
    "phoneNumbers": [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567" 
        }
    ] 
}

I want to read only the 'home' phone number not 'fax' phone number from the phoneNumbers json array. I don't want to use indexing to get the 'home' phone number.

1 Answers1

1

If you do not want to use indexing you could filter phoneNumbers array by property. Using JSONArray, JSONObject classes and Java 8 streams:

String json = Files.lines(Paths.get("src/main/resources/data.json")).collect(Collectors.joining());

JSONObject jsonObject = new JSONObject(json);
JSONArray phoneNumbers = jsonObject.getJSONArray("phoneNumbers");

String homeNumber = phoneNumbers.toList()
            .stream()
            .map(o -> (Map<String, String>) o)
            .filter(stringStringMap -> stringStringMap.get("type").equals("home"))
            .map(stringStringMap-> stringStringMap.get("number"))
            .findFirst()
            .orElse("unknown");

System.out.println(homeNumber);

This prints:

212 555-1234
Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63