如何从json数组读取特定的json对象元素?

时间:2019-06-04 18:03:34

标签: java json

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

我只想从phoneNumbers json数组中读取“家庭”电话号码,而不是“传真”电话号码。我不想使用索引来获取“家庭”电话号码。

1 个答案:

答案 0 :(得分:1)

如果您不想使用索引,则可以按属性过滤phoneNumbers数组。使用JSONArrayJSONObject类和Java 8流:

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);

此打印:

212 555-1234