Skip to main content

JSON Parsers

The JsonParser class parses JSON text into POJOs: beans, collections, maps and simple values.

When to use it​

Use JsonParser for input that must be strict RFC 8259 JSON. It enforces:

  • Double-quoted strings only (single quotes throw ParseException).
  • No comments, trailing commas, or unquoted keys.
  • JSON fragments (string, numeric, or boolean primitive values) are accepted.

For JSON5 input (single quotes, comments, trailing commas, unquoted keys), use Json5Parser; see JSON 5. For a one-line conversion with the default settings, Json.to(json, MyBean.class) is shorter; see Marshallers.

Example​

import org.apache.juneau.marshall.collections.*;
import org.apache.juneau.marshall.json.*;

public class JsonParserExample {

public static class Person {
public String name;
public int age;
}

public static void main(String[] args) throws Exception {
String json = "{\"name\":\"John Smith\",\"age\":45}";

// Parse into a bean with the default parser.
Person person = JsonParser.DEFAULT.read(json, Person.class);

// A parser that rejects trailing content, parsing into a generic map.
JsonParser parser = JsonParser.create().validateEnd().build();
JsonMap map = parser.read(json, JsonMap.class);
System.out.println(person.name + " " + map.get("age"));
}
}

With validateEnd(), input such as {"a":1}{"b":2} throws ParseException instead of stopping after the first object. Parsers are immutable and thread-safe, so build one once and reuse it.

Options​

The pre-configured instances:

InstanceAccepts
JsonParser.DEFAULTStrict JSON.
Json5Parser.DEFAULTJSON5.

For anything else, start from JsonParser.create(). The builder settings readers reach for first (all off by default):

Builder methodEffect
validateEnd()Fail if anything but whitespace follows the parsed value.
trimStrings()Trim whitespace from parsed string values.
autoCloseStreams()Close the input stream or reader when parsing finishes.
unbuffered()Read the input one character at a time, so several values can be read from one stream.
beanDictionary(Class...)Classes the parser may instantiate from _type properties.
swaps(Class...)Object swaps that convert parsed values into other types.

The builder inherits from this hierarchy, and each level's Javadoc lists the full set of settings:

Context.BuilderMarshallingContextable.BuilderParser.BuilderReaderParser.BuilderJsonParser.Builder

See also​