JEP 540:简单 JSON API(现已进入孵化阶段)
JEP 540: Simple JSON API (Now in Incubator)

原始链接: https://openjdk.org/jeps/540

本 JEP 提议引入一个孵化中的标准 Java API(`jdk.incubator.json`),用于解析和生成符合 RFC 8259 标准的 JSON。该 API 设计简洁、使用方便,使开发者无需依赖外部库即可处理 JSON 任务,这与 Java 近期对提升开发者生产力的关注相一致。 **核心特性:** * **极简设计:** 仅专注于核心 JSON 类型(对象、数组、字符串、数字、布尔值和 null),不包含数据绑定、流式处理或语法扩展等复杂功能。 * **易于使用:** 提供基于树的模型,通过 `JsonValue` 接口访问 JSON 数据。导航直观,且转换方法允许无缝提取为 Java 类型。 * **严格合规:** 强制严格遵守 RFC 8259 标准,包括禁止重复的对象键,以确保机器间通信的稳健性和可预测性。 * **弹性处理:** 包含 `tryGet` 和 `tryValue` 方法,可从容处理缺失字段或 null 值,使处理不断变化的文档结构变得更加容易。 通过提供一种原生的轻量级替代方案,该 API 减少了处理常见任务(如处理配置文件或 REST API 响应)时的依赖开销,并为未来需要结构化数据的平台特性奠定了基础。

```Hacker News 新帖 | 过往 | 评论 | 提问 | 展示 | 招聘 | 提交 登录 JEP 540:简易 JSON API(现已进入孵化阶段)(openjdk.org) 8 分,由 theanonymousone 发布于 30 分钟前 | 隐藏 | 过往 | 收藏 | 讨论 帮助 考虑申请 YC 2026 年秋季批次!申请截止日期为 7 月 27 日。 准则 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系 搜索:```
相关文章

原文

Summary

Define a simple, standard API for parsing and generating JSON documents so that doing so does not require an external library. Enable many JSON processing tasks to be accomplished with little coding. This is an incubating API.

History

This JEP supersedes JEP 198, Light-Weight JSON API, which was written in 2014. Circumstances have changed in the intervening years, so here we take a different approach.

Goals

  • Provide a standard means in the Java Platform to process RFC 8259 compliant JSON documents with low ceremony.
  • Keep the API small, simple, and easy to learn. Provide only those data types and operations required for strict conformance to RFC 8259, in order to facilitate machine-to-machine communication. Avoid features such as multiple parsing configurations, syntax extensions, data binding, and streaming.

  • Ensure that code that navigates and extracts data from JSON documents with a known structure is simple and readable. Because JSON documents do not have schemas, such code serves as a de facto schema and should be readable as such.

  • Enable easy and quick exploration of unfamiliar JSON documents. We often interact with JSON documents in an exploratory manner, writing code not using a specification but instead trying it out against example documents. The API should provide methods that fail fast with clear error messages, enabling quick exploration.

  • Ensure that missing or unexpected values can be handled in a resilient fashion, since JSON document structures can evolve over time.

  • Make the JDK itself capable of parsing and generating JSON documents.

Non-Goals

  • It is not a goal to create an API that supplants established external JSON libraries.

Motivation

JSON is ubiquitous in modern computing. The Java ecosystem contains a wide range of established JSON libraries: Jackson, Gson, Jakarta JSON Processing and Binding, Fastjson 2, and more. Not only do these libraries enable the parsing and generation of JSON documents, but they also support extended JSON syntaxes such as JSON5 and include higher-level features such as data binding, i.e., converting Java objects to and from JSON with a high degree of customization, and event-based streaming.

We often, however, just need to perform simple tasks such as extracting some data from a JSON document. The Python or Go code to accomplish such tasks is simple; the Java code should be equally simple.

For example, consider the task of computing the average of a set of forecast temperatures in a response from the U.S. National Weather Service REST API. The response is a JSON document that looks like this:

{
  ...
  "properties": {
    ...
    "periods": [
      {
        "number": 1,
        "name": "Today",
        "startTime": "2026-04-22T06:00:00-04:00",
        "endTime": "2026-04-22T18:00:00-04:00",
        "isDaytime": true,
        "temperature": 54,
        "temperatureUnit": "F",
        ...
      },
      {
        "number": 2,
        "name": "Tonight",
        "startTime": "2026-04-22T18:00:00-04:00",
        "endTime": "2026-04-23T06:00:00-04:00",
        "isDaytime": false,
        "temperature": 48,
        "temperatureUnit": "F",
        ...
      },
      {
        "number": 3,
        "name": "Thursday",
        "startTime": "2026-04-23T06:00:00-04:00",
        "endTime": "2026-04-23T18:00:00-04:00",
        "isDaytime": true,
        "temperature": 68,
        "temperatureUnit": "F",
        ...
      },
      ...
    ]
  }
}

To compute the average forecast temperature requires parsing the document, navigating to the location in the structure that contains the forecasts, and iterating over the array of forecasts while extracting the temperature data. We should be able to tackle simple tasks like this with simple Java code, without installing an external library and without suspecting that another language might make us more productive.

A key goal driving the recent evolution of the Java Platform has been to enable simple tasks to be accomplished more easily and with less ceremony. Features serving this goal include convenience factory methods for collections, var declarations, running programs from source files, and compact source files and instance main methods. A simple JSON API for parsing and generating JSON documents would also serve this important goal.

Using JSON in the JDK

A standard JSON API in the Java Platform would also pave the way for further use of JSON in the Platform and by the JDK itself, since the JDK cannot have external dependencies. One potential use case is configuration files. The JDK uses the property file format for various configuration files, such as security properties files. A weakness of this format is that it cannot express structured data. To represent an array in a property file, you must use clumsy workarounds such as sequentially numbered properties:

security.provider.1=SUN
security.provider.2=SunRsaSign
security.provider.3=SunEC
...

With JSON built into the JDK, configuration files could represent arrays naturally, using JSON arrays:

{
  "providers": [ "SUN", "SunRsaSign", "SunEC" ],
  ...
}

Description

The jdk.incubator.json API is organized around the JsonValue interface, which represents a JSON value.

The JSON syntax has four kinds of primitives:

  1. JSON strings, delimited with double quotes:

    "Hello"
    "My name is 'Bob'"
    "\u006a\u0061\u0076\u0061"
  2. JSON numbers, represented in base 10 using decimal digits:

    6  6.0  31.84  2.9E+5
  3. JSON boolean literals: true and false

  4. The JSON null literal: null

and two kinds of structures:

  1. JSON objects, delimited by { } and composed of comma-separated members. A member has a name, also called a key, and a value, separated by a colon:

    {
      "address" : "123 Smith Street",
      "value" : 31.84,
      "coordinates" : [ [ 37, 23, 41 ], [ -121, 57, 10 ] ]
    }
  2. JSON arrays, delimited by [ ] and composed of comma-separated JSON values:

    [ 1, 2, 3, { "value": "4" }, [ 5, 6 ] ]

The JsonValue interface thus has six corresponding sub-interfaces: JsonString, JsonNumber, JsonBoolean, JsonNull, JsonObject, and JsonArray. Each interface declares operations appropriate to its corresponding JSON syntactic element: Instances of the primitive sub-interfaces offer conversions to Java primitives and strings, JsonObject instances expose members, and JsonArray instances expose array elements.

The JsonValue interface is sealed, which guarantees that any JsonValue instance is always one of this fixed set of subtypes and thus exhaustive switch expressions and statements do not require a default clause.

The JSON API makes it easy to parse JSON documents that conform to RFC 8259. The parse method of the Json class returns a tree of JsonValue instances that expose the names, types, and values of the parsed JSON data. Returning to the National Weather Service example, we can compute the average forecast temperature in just a few lines:

String body = ... REST response body, which is a JSON document ... ;
JsonValue json = Json.parse(body);
json.get("properties").get("periods").asList().stream()
    .mapToInt(j -> j.get("temperature").asInt())
    .average()
    .ifPresent(IO::println);

(The complete example is shown in the Appendix.)

The API also makes it easy to generate JSON documents. For example, this code:

IO.println(JsonObject.of(Map.of("providers",
                                JsonArray.of(List.of(JsonString.of("SUN"),
                                                     JsonString.of("SunRsaSign"),
                                                     JsonString.of("SunEC"))))));

produces the output:

{"providers":["SUN","SunRsaSign","SunEC"]}

Parsing and navigating JSON documents

The Json class can parse a JSON document contained in either a String or a char array. A JSON document might be a REST API response body read from the network, a configuration file read from disk, or some other text payload produced by an application.

Parsing a JSON document requires a single call to one of the Json.parse methods:

JsonValue root = Json.parse(doc);

Parsing is strict: The document must conform to RFC 8259. Syntax extensions such as trailing commas and comments are not supported. Additionally, documents must not have objects with duplicate member names. This policy, permitted by the RFC, provides maximum interoperability and predictability, and reduces concerns about processing malformed or ambiguous JSON documents. (See below for a full discussion.)

Successful parsing returns an instance of JsonValue. Unsuccessful parsing throws an unchecked JsonParseException. The exception includes a detail message that provides specific information about the error and its location in the document. For example, the exception thrown when a document has duplicate member names in an object has the form:

jdk.incubator.json.JsonParseException: The duplicate member name: "foo" was
already parsed. Location: line 42, position 69

Most JSON documents have a JSON object or JSON array at the root. For example, a JSON-formatted thread dump produced by the jcmd tool contains a root object:

{
  "threadDump": {
    "formatVersion": 2,
    "processId": 45178,
    "time": "2026-04-16T23:13:02.709630Z",
    "runtimeVersion": "27-internal",
    "threadContainers": [
      {
        "container": "<root>",
        "parent": null,
        "owner": null,
        "threads": [
          {
            "tid": 3,
            "time": "2026-04-16T23:13:02.906891Z",
            "name": "main",
            "state": "WAITING",
            ...

The root object contains a single member, the nested threadDump object, and threadDump itself contains both primitive and structural JSON values.

Once you have obtained the root JsonValue via Json.parse(...), you can retrieve values from objects and arrays via their access methods, which return the requested member value or array element as a JsonValue.

  • get(String) obtains the value of an object member. To obtain the thread dump object:

    JsonValue threadDump = root.get("threadDump");
  • get(int) obtains an array element. To obtain the root thread container:

    JsonValue firstContainer = threadDump.get("threadContainers").get(0);

If the JsonValue instance is of the wrong type, or if the requested member or element does not exist, the access methods throw a JsonValueException.

Converting JSON values to Java values

You can convert a JSON value to a Java value by calling one of the conversion methods of the JsonValue interface. For a conversion to succeed, the JsonValue must be an instance of the appropriate subtype of JsonValue:

For example, you can retrieve the Java String value associated with the thread dump's "time" member:

JsonValue threadDumpTime = threadDump.get("time");
String time = threadDumpTime.asString();

You can convert the thread containers array into a List of JsonValue instances and process each instance:

threadDump.get("threadContainers").asList().forEach(jv -> ...);

You can access the thread dump object as a Map to retrieve the number of members:

int count = threadDump.asMap().size();

You can navigate deeply into a JSON document, chaining access methods and converting to a Java value only at the end. To retrieve the thread identifier value of the first thread in the root thread container:

long tid = threadDump.get("threadContainers").get(0)
                     .get("threads").get(0).get("tid").asLong();

The design of the conversion methods eliminates most instanceof checking and downcasting in cases where a specific JSON data type is expected in a document:

  • asString() converts a JsonString instance into a Java String with RFC 8259 JSON escape sequences translated to their corresponding characters.

  • asInt() converts a JsonNumber instance to a Java int if its numeric value can be represented exactly.

  • asLong() converts a JsonNumber instance to a Java long if its numeric value can be represented exactly.

  • asDouble() converts a JsonNumber instance to a Java double if its numeric value can be represented accurately.

  • asBoolean() converts a JsonBoolean instance to a Java boolean value of true or false.

  • asMap() converts a JsonObject instance into an unmodifiable Java Map. If the JSON object contains no members, an empty Map is returned.

  • asList() converts a JsonArray instance into an unmodifiable Java List. If the JSON array contains no elements, an empty List is returned.

There is no conversion method for the JSON null value. JsonNull instances can be handled by testing for instanceof JsonNull or via the tryValue method.

If a JsonValue is not an instance of the appropriate subtype for a conversion method then the method throws a JsonValueException. For example, calling asInt() on a JsonValue that is an instance of JsonString will always throw this exception. No attempt is made to parse the string value into a number.

Numeric conversions can fail for reasons such as the numeric value not being representable in the target Java numeric type, which also causes a JsonValueException to be thrown. See below for a deeper discussion of number handling and conversions.

Handling JSON document evolution

JSON documents from a particular source may evolve, over time, in ways that violate your previous expectations of their structure and content:

  • You might call access methods expecting member names or array indices that do not exist in the JSON objects and JSON arrays of the document.

  • You might call conversion methods applicable to one JSON type on values of a different type.

If you call access or conversion methods on the wrong type, they throw a JsonValueException. This exception is unchecked, so that scripts and small programs are easier to read and write.

Continuing with the thread dump example, recall that the root JSON value is a JSON object with a single member, threadDump. This code:

JsonValue name = root.get("threadName");

throws a JsonValueException because the JSON object does not contain a member with the name "threadName", while this code:

List<JsonValue> threadDumpList = threadDump.asList();

throws a JsonValueException because the threadDump member is a JSON object, not a JSON array.

The exception message describes the path leading from the root of the JSON document to the unexpected JSON value, as well as the position in the JSON document. This is helpful when a chain of access methods navigates deeply into the document. For example, if the earlier code snippet to extract the thread identifier incorrectly converted it to a boolean instead of a long:

boolean tid = threadDump.get("threadContainers").get(0)
                        .get("threads").get(0).get("tid").asBoolean();

then the exception thrown by asBoolean() would have the form:

jdk.incubator.json.JsonValueException: JsonNumber is not a JsonBoolean. Path:
 "{threadDump{threadContainers[0{threads[0{tid". Location: line 13, position 19.

Handling optional members

If you do not know whether a JSON object has a member with a given name, you can use the tryGet access method. This returns an Optional instance containing the member's value, or else an empty Optional if the member does not exist. (The get method, by contrast, confirms that the member exists and throws an exception if it does not.) The tryGet method throws a JsonValueException if it is not called on a JsonObject.

Consider the following thread object:

{
  "tid": 11,
  "time": "2026-04-16T23:13:02.918321Z",
  "name": "Finalizer",
  "state": "WAITING",
  "waitingOn": "java.lang.Object@c10f5b9",
  "stack": [
    ...

A thread object contains multiple optional members. One of them is the waitingOn member, which contains the JSON string representation of the object on which the thread is waiting. However, in cases where the thread is not waiting, the thread object may look like this:

{
  "tid": 10,
  "time": "2026-04-16T23:13:02.918177Z",
  "name": "Reference Handler",
  "state": "RUNNABLE",
  "stack": [
    ...

Thus, when processing thread objects from a thread dump, you must be prepared for the waitingOn member to be absent. You can handle this via tryGet:

JsonValue thread = ...
thread.tryGet("waitingOn")
      .ifPresent(result -> ...);

The lambda passed to ifPresent is called only if the waitingOn member is present.

Handling null values

If you do not know whether a JSON value is a JSON null, you can use the tryValue access method. This method returns an empty Optional if the JSON value upon which it is invoked is a JsonNull; otherwise, it returns that value.

For example, a thread container object typically looks like this:

{
  "container": "java.util.concurrent.ThreadPoolExecutor@1936a586",
  "parent": "<root>",
  ...

Here, the parent member's value is a JSON string, the parent container's name. However, the container named "<root>" is the root of all containers and looks like this:

{
  "container": "<root>",
  "parent": null,
  ...

The root container has no parent, so the parent member's value is a JSON null. Thus, when processing container objects from a thread dump, you must be prepared for the parent member to be either a JSON string or a JSON null. You can handle this via tryValue:

JsonValue container = ...
container.get("parent").tryValue()
         .ifPresent(result -> ...);

The lambda passed to ifPresent is called only if the "parent" member's value is not a JSON null.

Handling variable structure and content

The structure and content of JSON documents in a particular context is often uniform, but sometimes it is variable. It might vary across different sources, or over time from a particular source which itself evolves, or even within the same document.

For example, in thread dumps in JDK 26 and earlier releases, thread identifiers are represented as JSON strings; in JDK 27 and later releases, thread identifiers are represented as JSON numbers.

Code that expects the tid to be a JSON number, for example:

long tid = thread.get("tid").asLong();

will fail with a JsonValueException if it encounters a thread dump produced by a version of the JDK that emits tid values as JSON strings.

In either representation, the numeric value is specified to fit in a Java long. You could use instanceof to check whether you have a JsonNumber or a JsonString, but it is clearer to use type patterns in a switch statement:

long tid = switch (thread.get("tid")) {
    case JsonNumber jn -> jn.asLong();
    case JsonString js -> Long.parseLong(js.asString());
    default -> throw new JsonValueException("Unexpected type for \"tid\"");
};

Generating JSON documents

To generate a JSON document, in string form, from a JsonValue, simply invoke its toString method. This method returns a compact string representation in which all members, elements, and values are emitted on the same line, with no whitespace between them.

For example, this code:

JsonValue json = Json.parse("""
  {
    "service" : "web_server",
    "id" : 3
  }
  """);
IO.println(json.toString());

prints:

{"service":"web_server","id":3}

(The toString method is distinct from the asString method, which throws an exception if the JsonValue upon which it is invoked is not a JsonString.)

The static method Json.toDisplayString emits a pretty-printed form of a JSON document, where members and elements are separated by newlines and nested structures are indented by a given amount. For example, this code:

IO.println(Json.toDisplayString(json, 2));

prints the above structure with two spaces of indentation:

{
  "service": "web_server",
  "id": 3
}

The outputs of both the toString and Json.toDisplayString methods are parsable by the Json.parse method, which will produce a JsonValue that is equivalent to the original.

JSON numbers

The syntax for JSON numbers defined in RFC 8259 can represent decimal values of arbitrary precision and range. The JSON API enables JSON numbers to be processed losslessly; in most applications, however, common numeric types suffice.

RFC 8259 advises that good interoperability among JSON libraries can be achieved by using IEEE 754 64-bit binary floating point values, corresponding to the Java double type. The asDouble() method therefore converts a numeric JSON value to a Java double. The JSON value must lie within the range that a double can represent; if the value is out of range, a JsonValueException is thrown. Infinity and not-a-number ("NaN") values are not representable in JSON, and thus are never returned. Negative zero, however, is representable in JSON, and thus may be returned.

If the JSON value has more precision than can be represented in a double, the value is rounded to the closest double value. For example:

double d1 = Json.parse("3.141592653589793238462643383279").asDouble();
// d1 is 3.141592653589793, the nearest double value

double d2 = Json.parse("1.8E309").asDouble();
// throws JsonValueException, out of range

Integral numeric values are frequently used, so the asInt() method converts a numeric JSON value to a Java int value. The JSON value must be exactly representable as an int, otherwise an exception is thrown. Numbers that have a syntactic fractional part but that represent integral values are converted; for example:

int i1 = Json.parse("123.0").asInt();       // succeeds
int i2 = Json.parse("234.56E2").asInt();    // succeeds
int i3 = Json.parse("345.6").asInt();       // fails, not integral
int i4 = Json.parse("2147483648").asInt();  // fails, out of range

The conversion method asLong() is similar to asInt() except that it returns a Java long value and supports any JSON numeric value that can be represented exactly as a long.

If you need a narrower primitive type than int or double, you can use primitive types in patterns (currently a preview feature), to perform a safe conversion. For example, if you expect a JSON number to be representable as a short:

JsonValue json = Json.parse("""
  {
    "id": 12345,
    "price": 10.99
  }
  """);
if (json.get("id").asInt() instanceof short s) {
    // use s
} else {
    // report out-of-range error
}

As mentioned previously, JSON numbers can have arbitrary precision and range. The asDouble(), asInt(), and asLong() methods, by definition, handle only a subset of JSON numeric values; they reject out-of-range values, and they round overly-precise values. To handle JSON numeric data without loss of information, you can convert essentially any JSON number to a java.math.BigDecimal instance:

BigDecimal bd = new BigDecimal(jn.toString());

Alternatives

Testing

We will rigorously test the JSON API to ensure that only canonical forms of RFC 8259 JSON can be parsed and generated. This will help ensure that using the API will not result in inconsistencies when interacting with other JSON libraries. To accomplish this, we will not only add comprehensive unit tests to the JDK but also leverage the established JSON Parsing Test Suite, which contains numerous edge-case inputs.

Risks and Assumptions

  • We assume that input JSON documents can fit in memory, as either a String or a char array. Given our tree-based model, if we were to allow JSON sources such as files or network connections, issues such as insufficient memory would be possible with large documents. This decision aligns with our minimalist design philosophy.

  • A risk of this proposal is that this new API might end up being used in applications that are already using external JSON libraries, resulting in messiness and confusion. We believe this risk is outweighed by the benefits.

  • During the incubation period, we will gather more information about use cases involving generating and transforming JSON documents, in order to evolve these areas of the API. In addition, we will continue to consider forthcoming pattern-matching language features that might affect the design of the API.

Appendix: Weather Forecast Example

The following program issues a request to the U.S. National Weather Service REST API for a seven-day weather forecast for Santa Clara, CA. It receives a JSON document in the response body. The program then parses the document, navigates into the structure, and obtains an array of forecasts. It then extracts the temperature from each forecast, averages them, and prints the result.

import java.net.*;
import java.net.http.*;
import jdk.incubator.json.Json;
import jdk.incubator.json.JsonValue;

void main() throws Exception {
    var query = "https://api.weather.gov/gridpoints/MTR/97,83/forecast";
    var client = HttpClient.newHttpClient();
    var request = HttpRequest.newBuilder(URI.create(query)).build();
    var response = client.send(request, HttpResponse.BodyHandlers.ofString());
    String body = response.body();
    JsonValue json = Json.parse(response.body());
    json.get("properties").get("periods").asList().stream()
        .mapToInt(j -> j.get("temperature").asInt())
        .average()
        .ifPresent(IO::println);
}

Enabling the incubating API

The JSON API is, at present, an incubator module, disabled by default. To use it, you must enable it via the command-line option --add-modules jdk.incubator.json, which adds the incubator module to the set of modules available for resolution. To run the above example program, you must provide this option at both compile time and run time.

To run the average forecast program as a single-file source code program, do this:

$ java --add-modules jdk.incubator.json Weather.java

The output will be something like:

WARNING: Using incubator modules: jdk.incubator.json
53.357142857142854

To compile the program with javac and run it with java, do this:

$ javac --add-modules jdk.incubator.json Weather.java
$ java --add-modules jdk.incubator.json Weather

You can use jshell to experiment interactively with the API. As before, you must enable the incubator module on the command line:

$ jshell --add-modules jdk.incubator.json
jshell> import jdk.incubator.json.*
jshell> Json.parse("""
   ...> { "name": "Today", "temperature": 54 }
   ...> """)
$2 ==> {"name":"Today","temperature":54}
jshell> $2.get("temperature").asInt()
$3 ==> 54
jshell>
联系我们 contact @ memedata.com