Package jdk.incubator.json
package jdk.incubator.json
This API supports processing of JSON text in a simple manner. It is organized around the
A successful parse indicates that the JSON text adheres to the JSON grammar.
Unsuccessful parsing throws a
the JSON string "SUN" can be accessed as follows:
If an access method is invoked on an incompatible JSON type, for example,
calling
This example only prints the value if the member named "providers" exists.
This example only prints the value if the member named "providers" is not a JSON
null.
While the code above throws an exception if the type is neither
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
The code above retrieves the Java String
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 eitherJson.parse(java.lang.String) or Json.parse(char[]).
JsonValue json = Json.parse(text);
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 aJsonValue 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 }
""");
JsonValue firstProvider = json.get("providers").get(0);
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 methodJsonValue.tryGet(String) which returns an Optional of JsonValue.
For example:
json.tryGet("providers")
.ifPresent(IO::println);
Handling null values
Sometimes, JSON null is used to signify absence of a member. In this scenario, use the access methodJsonValue.tryValue() which returns an
Optional of JsonValue. For example:
json.get("providers")
.tryValue()
.ifPresent(IO::println);
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");
}
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");
"none" fallback value is used over throwing an exception.
Converting JSON values to Java values
Once you have navigated to your desiredJsonValue, use the conversion methods to produce
a corresponding Java value. Each conversion method requires a particular JSON type:
asString()converts aJsonStringinstance into a JavaStringwith RFC 8259 JSON escape sequences translated to their corresponding characters.asInt()converts aJsonNumberinstance to a Javaintif its numeric value can be represented exactly.asLong()converts aJsonNumberinstance to a Javalongif its numeric value can be represented exactly.asDouble()converts aJsonNumberinstance to a Javadoubleif its numeric value can be rounded to a finite Javadouble.asBoolean()converts aJsonBooleaninstance to a Javabooleanvalue oftrueorfalse.asMap()converts aJsonObjectinstance into an unmodifiable JavaMap. If the JSON object contains no members, an emptyMapis returned.asList()converts aJsonArrayinstance into an unmodifiable JavaList. If the JSON array contains no elements, an emptyListis returned.
String sun = firstProvider.asString();
"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 eitherJsonValue.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
-
ClassDescriptionThis 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.