Package jdk.incubator.json


package jdk.incubator.json
This API supports processing of JSON text in a simple manner. It is organized around the JsonValue interface which represents a JSON value, and the Json class which provides methods to parse and generate JSON text. Typical usage of this API involves first parsing JSON text into a JsonValue, navigating the parsed JSON value to the desired JSON value using access methods, and lastly converting the desired value using a conversion method. For example:
List<JsonValue> providers = Json.parse(text)
         .get("providers") // access
         .asList(); // conversion

Parsing JSON text

Parsing JSON text can be done using either Json.parse(java.lang.String) or Json.parse(char[]).
JsonValue json = Json.parse(text);
A successful parse indicates that the JSON text adheres to the JSON grammar. Unsuccessful parsing throws a JsonParseException, which provides a detail message that includes error details, a path to the root of the JSON text, and its location within the text. The parsing APIs do not accept JSON text that contains JSON objects with duplicate member names.

The result of a successful parse is a JsonValue. The JsonValue interface has six sub-interfaces: JsonString, JsonNumber, JsonBoolean, JsonNull, JsonObject, and JsonArray. Each sub-interface corresponds to one of the elements of JSON syntax. This type hierarchy allows you to use pattern matching to determine the subtype of a JsonValue. JsonValue instances are immutable and thread safe.

Navigating JSON text

Once you have obtained a JsonValue from parsing, use the access methods to navigate through JSON structural elements. JsonValue.get(String) is provided for JSON objects and JsonValue.get(int) for JSON arrays. Given the JSON text:
JsonValue json = Json.parse("""
    { "providers": [ "SUN", "SunRsaSign", "SunEC" ], "version": 1 }
    """);
the JSON string "SUN" can be accessed as follows:
JsonValue firstProvider = json.get("providers").get(0);
If an access method is invoked on an incompatible JSON type, for example, calling get(String) on a JSON array, a JsonValueException is thrown.

Handling optional members

A member of a JSON object can be optional. In this scenario, use the access method JsonValue.tryGet(String) which returns an Optional of JsonValue. For example:
json.tryGet("providers")
    .ifPresent(IO::println);
This example only prints the value if the member named "providers" exists.

Handling null values

Sometimes, JSON null is used to signify absence of a member. In this scenario, use the access method JsonValue.tryValue() which returns an Optional of JsonValue. For example:
json.get("providers")
    .tryValue()
    .ifPresent(IO::println);
This example only prints the value if the member named "providers" is not a JSON null.

Handling variance in type or structure

If the type for a JSON value is variable, it can be handled as follows:
String firstProvider = switch (json.get("providers")) {
    case JsonString js -> js.asString(); // handle the value as JSON string
    case JsonArray ja -> ja.get(0).asString(); // handle the value as JSON array
    default -> throw new JsonValueException("unexpected type");
}
While the code above throws an exception if the type is neither JsonString nor JsonArray, there are times when you may prefer a fallback value instead. For example:
String firstProvider = Optional.of(json)
    .filter(j -> j instanceof JsonObject)
    .flatMap(j -> j.tryGet("providers"))
    .filter(j -> j instanceof JsonString)
    .map(JsonValue::asString)
    .orElse("none");
This code ensures that if the root JSON value is not an object, the member "providers" does not exist, or if the value of "providers" is not a JSON String, then the "none" fallback value is used over throwing an exception.

Converting JSON values to Java values

Once you have navigated to your desired JsonValue, use the conversion methods to produce a corresponding Java value. Each conversion method requires a particular JSON type:
  • 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 rounded to a finite Java double.
  • 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.
For example:
String sun = firstProvider.asString();
The code above retrieves the Java String "SUN" from the JSON value firstProvider. If an incorrect conversion method is used, which does not correspond to the matching JSON type, for example firstProvider.asBoolean(), a JsonValueException is thrown.

Most conversion methods always return a value when the JsonValue is of the correct JSON type. The exceptions are asInt(), asLong(), and asDouble(); they may throw a JsonValueException even when the JsonValue is a JSON number, for example if it is outside their supported ranges.

Generating JSON text

Generating JSON text is performed with either JsonValue.toString() or Json.toDisplayString(JsonValue, String). These methods produce String representations of a JsonValue that adhere to the JSON grammar defined in RFC 8259. JsonValue.toString() produces compact JSON text which does not include JSON insignificant whitespace, preferable for network transmission or storage. For example:
{"providers":["SUN","SunRsaSign","SunEC"],"version":1}
Json.toDisplayString(JsonValue, String) produces pretty-printed JSON text which is easier to read, preferable for debugging or logging. For example:
{
  "providers": [
    "SUN",
    "SunRsaSign",
    "SunEC"
  ],
  "version": 1
}
Since:
28
External Specifications
  • Class
    Description
    This class provides static methods for parsing and generating JSON texts.
    The interface that represents JSON array.
    The interface that represents the JSON boolean literals, "true" and "false".
    The interface that represents JSON null.
    The interface that represents JSON number, an arbitrary-precision number represented in base 10 using decimal digits.
    The interface that represents JSON object.
    Signals that an error has been detected while parsing the JSON text.
    The interface that represents JSON string.
    The interface that represents a JSON value.
    Indicates that an error has been detected while operating on the JsonValue.