Overview of JSON Pointer – JSON 指针的概述

最后修改: 2018年 8月 17日

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

1. Overview

1.概述

In this tutorial, we’ll show how to use JSON Pointer to navigate and fetch information from JSON data.

在本教程中,我们将展示如何使用JSON Pointer来浏览和获取JSON数据的信息

We’ll also show how to perform operations such as inserting new data or updating existing key-values.

我们还将展示如何执行插入新数据或更新现有键值等操作。

2. Dependency Setup

2.依赖性设置

First, we need to add some dependencies to our pom.xml:

首先,我们需要向我们的pom.xml添加一些依赖项。

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1.2</version>
</dependency>

3. JSON Pointer

3.JSON 指针

JSON (“JavaScript Object Notation”) is a lightweight format for exchanging data between systems, originally specified by Douglas Crockford.

JSON(”JavaScript Object Notation”)是一种用于在系统之间交换数据的轻量级格式,最初由Douglas Crockford指定。

Although it uses JavaScript syntax, it’s language-independent, since the resultant is plain text.

虽然它使用了JavaScript语法,它是独立于语言的,因为结果是纯文本

JSON Pointer (RFC 6901) is a feature from JSON Processing 1.1 API (JSR 374). It defines a String that can be used for accessing values on a JSON document. It can be related to what XPath does for an XML document.

JSON指针(RFC 6901)是JSON处理1.1 API(JSR 374)中的一项功能。它定义了一个String,可用于访问JSON文档上的值。它可以与XPath对XML文档的作用有关。

Through the use of JSON Pointer, we can fetch data from and alter a JSON file.

通过使用JSON Pointer,我们可以从JSON文件中获取数据,并改变JSON文件。

4. Accessing Data

4.访问数据

We’ll see some examples of how to perform operations by implementing a class called JsonPointerCrud.

我们将看到一些例子,说明如何通过实现一个名为JsonPointerCrud的类来进行操作。

Let’s suppose we have a JSON file called books.json with the content:

假设我们有一个名为books.json的JSON文件,内容是。

{
    "library": "My Personal Library",
    "books": [
        { "title":"Title 1", "author":"Jane Doe" },
        { "title":"Title 2", "author":"John Doe" }
    ]
}

To access the data from that file, we need to read it and parse it to a JsonStructure. We can achieve it using Json.createReader() method, which accepts an InputStream or a FileReader.

为了访问该文件中的数据,我们需要读取它并将其解析为JsonStructure。我们可以使用Json.createReader()方法来实现,它接受一个InputStreamFileReader

Here’s how we can do that:

下面是我们如何做到这一点。

JsonReader reader = Json.createReader(new FileReader("books.json"));
JsonStructure jsonStructure = reader.read();
reader.close();

The content will be stored on a JsonStructure object. This is the object we’ll use to perform next operations.

这些内容将被存储在一个JsonStructure对象上。这是我们将用来执行下一步操作的对象。

4.1. Fetch Data from the File

4.1.从文件中获取数据

To fetch a single value we create a JsonPointer, informing which tag we want to get the value from:

为了获取一个单一的值,我们创建一个JsonPointer,告知我们要从哪个标签获取值。

JsonPointer jsonPointer = Json.createPointer("/library");
JsonString jsonString = (JsonString) jsonPointer.getValue(jsonStructure);
System.out.println(jsonString.getString());

Note that the first character of this String is a ‘/’ – this is a syntactic requirement.

请注意,这个String的第一个字符是’/’ – 这是一个句法要求

The result of this snippet is:

这个片段的结果是。

My Personal Library

To fetch a value from a list, we need to specify its index (where the first index is 0):

要从一个列表中获取一个值,我们需要指定其索引(其中第一个索引是0)。

JsonPointer jsonPointer = Json.createPointer("/books/1");
JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure);
System.out.println(jsonObject.toString());

This outputs:

这个产出。

"title":"Title 2", "author":"John Doe"

4.2. Check If a Key Is Present in the File

4.2.检查文件中是否存在一个键

Through the method containsValue, we can check if the value used to create the pointer is present on the JSON file:

通过方法containsValue,我们可以检查用于创建指针的值是否存在于JSON文件中。

JsonPointer jsonPointer = Json.createPointer("/library");
boolean found = jsonPointer.containsValue(jsonStructure);
System.out.println(found);

The result for this snippet is:

这个片段的结果是。

true

4.3. Insert New Key-Value

4.3.插入新的键值

If we need to add a new value to the JSON, the createValue is the one to handle it. The method createValue is overloaded to accept String, int, long, double, BigDecimal and BigInteger:

如果我们需要向JSON添加一个新的值,createValue就是要处理的。方法createValue被重载以接受StringintlongdoubleBigDecimalBigInteger:

JsonPointer jsonPointer = Json.createPointer("/total");
JsonNumber jsonNumber = Json.createValue(2);
jsonStructure = jsonPointer.add(jsonStructure, jsonNumber);
System.out.println(jsonStructure);

Again, our output is:

同样,我们的输出是。

{
    "library": "My Personal Library",
    "total": 2,
    "books": [
        { "title":"Title 1", "author":"Jane Doe" },
        { "title":"Title 2", "author":"John Doe" }
    ]
}

4.4. Update a Key-Value

4.4.更新一个键值

To update a value we need to create the new value first. After the value is created, we use the replace method from the pointer created using the key parameter:

为了更新一个值,我们需要先创建新的值。在值被创建后,我们使用replace方法,从使用key参数创建的指针中取出。

JsonPointer jsonPointer = Json.createPointer("/total");
JsonNumber jsonNumberNewValue = Json.createValue(5);
jsonStructure = jsonPointer.replace(jsonStructure, jsonNumberNewValue);
System.out.println(jsonStructure);

Outputting:

输出。

{
    "library": "My Personal Library",
    "total": 5,
    "books": [
        { "title":"Title 1", "author":"Jane Doe" },
        { "title":"Title 2", "author":"John Doe" }
    ]
}

4.5. Remove a Key

4.5.移除一个钥匙

To remove a key, we first create a pointer to the key. We then use the remove method:

要删除一个键,我们首先创建一个指向该键的指针。然后我们使用删除方法。

JsonPointer jsonPointer = Json.createPointer("/library");
jsonPointer.getValue(jsonStructure);
jsonStructure = jsonPointer.remove(jsonStructure);
System.out.println(jsonStructure);

Resulting in:

导致。

{
    "total": 5,
    "books": [
        { "title":"Title 1", "author":"Jane Doe" },
        { "title":"Title 2", "author":"John Doe" }
    ]
}

4.6. Show the Full Content of the File

4.6.显示文件的全部内容

If the pointer is created with an empty String, the whole content is retrieved:

如果创建的指针是空的String,就会检索到整个内容。

JsonPointer jsonPointer = Json.createPointer("");
JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure);
System.out.println(jsonObject.toString());

This code sample would output the whole contents of the jsonStructure.

这个代码示例将输出jsonStructure的全部内容。

5. Conclusion

5.结论

In this quick article, we’ve covered how to work with JSON Pointer to perform various operations on JSON data.

在这篇快速文章中,我们已经介绍了如何使用JSON指针对JSON数据进行各种操作。

And, as usual, the code related to this tutorial is over on GitHub.

而且,像往常一样,与本教程有关的代码在GitHub上