Package javax.json 是一个 Java API,提供了处理 JSON 数据(JavaScript Object Notation,JavaScript 对象表示法)的方法。它支持 JSON 对象的创建、读取、修改和写入。这个库是 Java EE 的一部分,但也可以单独使用于 Java SE 环境中。
javax.json API 提供了一组简洁的类和接口,使得开发者可以更加方便地处理 JSON 数据格式。例如,可以使用 Json.createObjectBuilder()
方法来构建 JSON 对象,使用 Json.createReader(InputStream)
方法来读取 JSON 数据等。
此外,javax.json 还支持 JSON 的流式处理,这在处理大型 JSON 数据时尤其有用。通过流式处理,可以在不将整个 JSON 文档加载到内存的情况下解析和生成 JSON 数据。
总的来说,javax.json 是一个功能强大且灵活的 JSON 处理库,适用于各种需要处理 JSON 数据的 Java 应用程序。
Package javax.json 是一个 Java API,提供了处理 JSON 数据(JavaScript Object Notation,JavaScript 对象表示法)的方法。这个包包含了一系列类和接口,用于创建、解析、生成和操作 JSON 数据。
主要功能包括:
- JSON 创建:提供构建 JSON 对象和数组的工具。
- JSON 解析:从字符串或流中读取 JSON 数据并转换为相应的 JSON 对象。
- JSON 生成:将 JSON 对象转换为字符串格式以便于传输或存储。
- JSON 操作:对 JSON 对象进行查询、修改和删除操作。
常用的类和接口有:
JsonObject
:表示一个 JSON 对象,类似于一个键值对的集合。JsonArray
:表示一个 JSON 数组,可以包含多个 JSON 值。JsonValue
:所有 JSON 类型的基类,包括对象、数组、字符串、数字、布尔值和空值。JsonReader
和JsonWriter
:用于读取和写入 JSON 数据。
示例代码:
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonArray;
import javax.json.JsonReader;
import java.io.StringReader;
// 创建一个 JSON 对象
JsonObject jsonObject = Json.createObjectBuilder()
.add("name", "John Doe")
.add("age", 30)
.build();
// 创建一个 JSON 数组
JsonArray jsonArray = Json.createArrayBuilder()
.add(1)
.add(2)
.add(3)
.build();
// 将 JSON 对象转换为字符串
String jsonString = jsonObject.toString();
System.out.println(jsonString);
// 从字符串解析 JSON 对象
JsonReader reader = Json.createReader(new StringReader(jsonString));
JsonObject parsedJsonObject = reader.readObject();
reader.close();
System.out.println(parsedJsonObject.getString("name")); // 输出: John Doe
在 Java 中使用 javax.json
包来解析嵌套的 JSON 数据,可以通过以下几个步骤来实现。javax.json
是 Java EE 7 引入的一个标准 API,用于处理 JSON 数据。
步骤一:添加依赖
确保你的项目中包含 javax.json
的依赖。如果你使用 Maven 构建工具,可以在 pom.xml
文件中添加以下依赖:
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1.4</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1.4</version>
</dependency>
步骤二:创建 JSON 对象
首先,你需要从字符串或输入流中创建一个 JsonReader
对象,然后使用它来读取 JSON 数据并生成 JsonObject
或 JsonArray
对象。
步骤三:解析嵌套的 JSON 数据
通过递归地遍历 JsonObject
和 JsonArray
,你可以访问嵌套的 JSON 数据。以下是一个完整的示例代码,演示如何解析一个嵌套的 JSON 数据:
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import java.io.StringReader;
public class ParseNestedJSON {
public static void main(String[] args) {
String jsonString = "{ \"name\": \"John\", \"age\": 30, \"address\": { \"street\": \"21 2nd Street\", \"city\": \"New York\" }, \"phoneNumbers\": [ { \"type\": \"home\", \"number\": \"212 555-1234\" }, { \"type\": \"office\", \"number\": \"646 555-4567\" } ] }";
try (JsonReader reader = Json.createReader(new StringReader(jsonString))) {
JsonObject jsonObject = reader.readObject();
parseJsonObject(jsonObject, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void parseJsonObject(JsonObject jsonObject, int level) {
jsonObject.entrySet().forEach(entry -> {
System.out.println(" ".repeat(level * 2) + entry.getKey() + ": " + entry.getValue());
if (entry.getValue() instanceof JsonObject) {
parseJsonObject((JsonObject) entry.getValue(), level + 1);
} else if (entry.getValue() instanceof JsonArray) {
parseJsonArray((JsonArray) entry.getValue(), level + 1);
}
});
}
private static void parseJsonArray(JsonArray jsonArray, int level) {
jsonArray.forEach(value -> {
System.out.println(" ".repeat(level * 2) + value);
if (value instanceof JsonObject) {
parseJsonObject((JsonObject) value, level + 1);
} else if (value instanceof JsonArray) {
parseJsonArray((JsonArray) value, level + 1);
}
});
}
}
解释
- 添加依赖:确保项目中包含
javax.json
的依赖。 - 创建 JSON 对象:使用
JsonReader
从字符串中读取 JSON 数据,并生成JsonObject
。 - 解析嵌套的 JSON 数据:通过递归地遍历
JsonObject
和JsonArray
,打印出所有键值对及其嵌套结构。
Skip navigation links
Overview
Package
Class
Use
Tree
Deprecated
Index
Help
Prev Package
Next Package
Frames
No Frames
Package javax.json
Provides an object model API to process JSON.
See: Description
Interface Summary Interface Description
JsonArray
JsonArray represents an immutable JSON array (an ordered sequence of zero or more values).
JsonArrayBuilder
A builder for creating JsonArray models from scratch, and for modifying a existing JsonArray.
JsonBuilderFactory
Factory to create JsonObjectBuilder and JsonArrayBuilder instances.
JsonMergePatch
This interface represents an implementation of a JSON Merge Patch as defined by RFC 7396.
JsonNumber
An immutable JSON number value.
JsonObject
JsonObject class represents an immutable JSON object value (an unordered collection of zero or more name/value pairs).
JsonObjectBuilder
A builder for creating JsonObject models from scratch.
JsonPatch
This interface represents an immutable implementation of a JSON Patch as defined by RFC 6902.
JsonPatchBuilder
A builder for constructing a JSON Patch as defined by RFC 6902 by adding JSON Patch operations incrementally.
JsonPointer
This interface represents an immutable implementation of a JSON Pointer as defined by RFC 6901.
JsonReader
Reads a JSON object or an array structure from an input source.
JsonReaderFactory
Factory to create JsonReader instances.
JsonString
An immutable JSON string value.
JsonStructure
Super type for the two structured types in JSON (objects and arrays).
JsonValue
JsonValue represents an immutable JSON value.
JsonWriter
Writes a JSON object or array structure to an output source.
JsonWriterFactory
Factory to create JsonWriter instances.
Class Summary Class Description
Json
Factory class for creating JSON processing objects.
Enum Summary Enum Description
JsonPatch.Operation
This enum represents the list of valid JSON Patch operations as defined by RFC 6902.
JsonValue.ValueType
Indicates the type of a JsonValue object.
Exception Summary Exception Description
JsonException
JsonException indicates that some exception happened during JSON processing.
Package javax.json Description
Provides an object model API to process JSON.
The object model API is a high-level API that provides immutable object models for JSON object and array structures. These JSON structures are represented as object models using the Java types JsonObject and JsonArray. The interface javax.json.JsonObject provides a Map view to access the unordered collection of zero or more name/value pairs from the model. Similarly, the interface JsonArray provides a List view to access the ordered sequence of zero or more values from the model.
The object model API uses builder patterns to create and modify these object models. The classes JsonObjectBuilder and JsonArrayBuilder provide methods to create and modify models of type JsonObject and JsonArray respectively.
These object models can also be created from an input source using the class JsonReader. Similarly, these object models can be written to an output source using the class JsonWriter.
This package includes several classes that implement other JSON related standards: JSON Pointer, JSON Patch, and JSON Merge Patch. They can be used to retrieve, transform or manipulate values in an object model.
Skip navigation links
Overview
Package
Class
Use
Tree
Deprecated
Index
Help
Prev Package
Next Package
Frames
No Frames
Copyright © 1996-2017, Oracle and/or its affiliates. All Rights Reserved. Use is subject to license terms.
在 Java 中将 JSON 数据转换为 Java 对象,通常使用 Jackson 或 Gson 这两个流行的库。下面以 Jackson 为例进行介绍:
首先,需要添加 Jackson 的依赖。如果你使用的是 Maven,可以在 pom.xml
文件中添加以下依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
接下来,假设你有一个 JSON 字符串如下:
{
"name": "John",
"age": 30,
"city": "New York"
}
你可以创建一个对应的 Java 类,例如 Person
:
public class Person {
private String name;
private int age;
private String city;
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
然后,使用 Jackson 的 ObjectMapper
类来将 JSON 字符串转换为 Java 对象:
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) {
try {
String jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
ObjectMapper objectMapper = new ObjectMapper();
Person person = objectMapper.readValue(jsonString, Person.class);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
System.out.println("City: " + person.getCity());
} catch (Exception e) {
e.printStackTrace();
}
}
}
上述代码通过 Jackson 的 ObjectMapper
类将 JSON 字符串解析为 Person
类的实例,并输出相应的属性值。