Get a Value by Key in a JSONArray – 在JSONArray中按键获取一个值

最后修改: 2018年 10月 28日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

JSON is a light-weight and language independent data-interchange format used for most client-server communications.

JSON是一种轻量级和独立于语言的数据交换格式,用于大多数客户-服务器通信。

JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.

JSONObjectJSONArray是大多数JSON处理库中通常提供的两个普通类。一个JSONObject存储无序的键值对,很像Java的Map实现。一个JSONArray,另一方面,是一个有序的值序列,很像Java中的ListVector

In this tutorial, we’ll be using JSON-Java (org.json) library and learn how to process a JSONArray to extract value for a given key. If needed, we have available an introduction to this library.

在本教程中,我们将使用JSON-Javaorg.json)库,并学习如何处理JSONArray以提取指定键的值。如果需要,我们有这个库的介绍

2. Maven Dependency

2.Maven的依赖性

We’ll first start by adding the below dependency in our POM:

我们首先在我们的POM中添加以下依赖关系。

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
</dependency>

We can always find out the latest version of JSON-Java on Maven Central.

我们可以随时在Maven Central上查到JSON-Java的最新版本。

3. Context Buildup

3.语境的建立

A JSON message is usually comprised of JSON objects and arrays which may be nested inside one another. A JSONArray object is enclosed within square brackets [ ] whereas a JSONObject is enclosed within curly braces {}. For instance, let’s consider this JSON message:

一个JSON信息通常由JSON对象和数组组成,它们可以相互嵌套。一个JSONArray对象被括在方括号内 [ ],而一个JSONObject被括在大括号内{}。例如,让我们考虑这个JSON信息。

[
    {
        "name": "John",
        "city": "chicago",
        "age": "22"
    },
    {
        "name": "Gary",
        "city": "florida",
        "age": "35"
    },
    {
        "name": "Selena",
        "city": "vegas",
        "age": "18"
    }
]

Clearly, it’s an array of JSON objects. Each JSON object in this array represents our customer record having a name, age, and city as its attributes or keys.

很明显,这是一个JSON对象的数组。这个数组中的每个JSON对象代表我们的客户记录,有姓名、年龄和城市作为其属性或键。

4. Processing JSONArray

4.处理JSONArray

Given the above JSON, what if we wish to find out the names of all our customers? In other words, given a key, “name” in our example, how can we go about finding all the values mapped to that key in a given JSON array?

鉴于上述JSON,如果我们希望找出我们所有客户的名字,该怎么办?换句话说,给定一个键,“name” 在我们的例子中,我们如何在给定的JSON数组中找到映射到该键的所有值?

As we know, a JSONArray is a list of JSON objects. So, let’s find all values for a given key:

正如我们所知,JSONArray是一个JSON对象的列表。因此,让我们找到一个给定键的所有值。

public List<String> getValuesForGivenKey(String jsonArrayStr, String key) {
    JSONArray jsonArray = new JSONArray(jsonArrayStr);
    return IntStream.range(0, jsonArray.length())
      .mapToObj(index -> ((JSONObject)jsonArray.get(index)).optString(key))
      .collect(Collectors.toList());
}

In the previous example:

在前面的例子中。

  • Firstly, we iterate through the entire list of objects in a JSON array
  • Then for each JSONObject, we get the value mapped to the given key

Also, the method optString() returns an empty string if no such key exists.

另外,如果不存在这样的键,方法optString()会返回一个空字符串。

On invoking getValuesForGivenKey(jsonArrayStr, “name”) where jsonArrayStr is our example JSON, we’ll get a List of all names as the output:

在调用getValuesForGivenKey(jsonArrayStr, “name”) 时, jsonArrayStr 是我们的示例JSON,我们将得到一个所有名字的List作为输出。

[John, Gary, Selena]

5. Conclusion

5.总结

In this quick article, we learned how to parse a JSONArray to get all the mapped values for a given key. Here, we have used JSON-Java (org.json) library.

在这篇文章中,我们学习了如何解析一个JSONArray,以获得一个给定键的所有映射值。在这里,我们使用了JSON-Java(org.json)库。

JSON.simple is yet another similar and powerful alternative for working with JSON in Java. Please feel free to explore.

JSON.simple是另一个类似的、强大的替代品,用于在Java中处理JSON。请自由探索。

As usual, the complete source code is available over on Github.

像往常一样,完整的源代码可以在Github上获得