Json#

A strict JSON parser and a canonical JSON writer. parse turns JSON text into a tree of plain Java values. stringify writes such a tree back as compact JSON with sorted keys. Json has only static methods and no instances. It holds no state, so both methods are safe to call from any thread.

The trees that Wire.envelope and Wire.error return, and the input of Decode.fromValue, use the same value types.

Declaration#

public final class Json

Static methods#

parse#

public static Object parse(String text)

Parses one JSON document. Each JSON value maps to a Java type:

JSON Java
object Map<String, Object>, keys in document order
array List<Object>
string String
true, false Boolean
null null
integer literal (no fraction, no exponent) that fits in a long Long
any other number Double

Read numbers as Number, because the same field can come back as a Long or a Double. A Double holds the nearest double, so a parse and stringify round trip keeps at most 17 significant digits: 9007199254740993.0 comes back as 9007199254740992. An integer literal outside the long range also becomes a Double. -0 parses as 0L, so the sign is lost. A literal beyond the double range, such as 1e400, parses to an infinity, which stringify rejects.

The parser is strict. It rejects duplicate object keys, trailing characters after the document, unescaped control characters in strings and invalid escapes. Whitespace between tokens is space, tab, \n and \r only.

Parameters

Name Type Description
text String One JSON document

Returns - the parsed value: a Map, List, String, Boolean, Long, Double or null.

Errors - throws IllegalArgumentException when text isn't valid JSON or repeats a key in an object. The message names the problem and the position, for example duplicate field `id` at character N. Throws NullPointerException when text is null.

stringify#

public static String stringify(Object value)

Writes value as compact JSON with no whitespace. The output is canonical, so equal trees always give the same text:

  • object keys are sorted by String.compareTo (UTF-16 code unit order)
  • every Number type (Long, Integer, Double, Float, BigDecimal, BigInteger, ...) is written the same way: no trailing zeros, plain notation between 1e-6 and 1e21, e-notation outside that range, and every zero, including -0.0, as 0
  • a Float is formatted from its own decimal text, so 0.1f is written as 0.1
  • strings escape ", \ and control characters; other characters, including non-ASCII, are written as they are

Parameters

Name Type Description
value Object The value to write; may be null

Accepted value types:

Java JSON
null null
String string
Boolean true / false
Number number
Map<String, ?> object
Iterable (List, Set, ...) array
array (object or primitive) array

Returns - the JSON text.

Errors - throws IllegalArgumentException when the tree contains a NaN or infinite number, or a value of any other type (a record, an enum, a Moment). To write a typed result, use Encode.text.

Example#

import java.util.List;
import java.util.Map;
import org.dhtmlx.plen.Json;

public class JsonExample {
  @SuppressWarnings("unchecked")
  public static void main(String[] args) throws Exception {
    var task = (Map<String, Object>) Json.parse(
        "{\"id\": 7, \"duration\": 2.50, \"tags\": [\"design\"], \"parent\": null}");

    Number id = (Number) task.get("id");             // Long 7
    Number duration = (Number) task.get("duration"); // Double 2.5
    System.out.println(id.longValue() + " " + duration.doubleValue());

    System.out.println(Json.stringify(task));
    // {"duration":2.5,"id":7,"parent":null,"tags":["design"]}

    System.out.println(Json.stringify(Map.of("units", 1.0f, "slices", List.of(0.5, -0.0))));
    // {"slices":[0.5,0],"units":1}
  }
}