Java API for JSON Processing

JSR 374 Specification

Getting Started Download

What is JSON-P?

JSON Processing (JSON-P) is a Java API to process (for e.g. parse, generate, transform and query) JSON messages. It produces and consumes JSON text in a streaming fashion (similar to StAX API for XML) and allows to build a Java object model for JSON text using API classes (similar to DOM API for XML).

Consistent

Consistent with JAXP (Java API for XML Processing) and other Java EE and SE APIs where appropriate

Conventional

Define default mapping of Java classes and instances to JSON document counterparts

Customizable

Allow customization of the default JSON service provider

Easy to Use

Default use of the APIs should not require prior knowledge of the JSON document format and specification


To print/parse a Java Object to/from JSON

JSON-P Object Model calls

public static void main(String[] args) {
   // Create Json and serialize
   JsonObject json = Json.createObjectBuilder()
     .add("name", "Falco")
     .add("age", BigDecimal.valueOf(3))
     .add("biteable", Boolean.FALSE).build();
   String result = json.toString();
     
   System.out.println(result);
 }

JSON-P Streaming API calls

public static void main(String[] args) {
    // Parse back
    final String result = "{\"name\":\"Falco\",\"age\":3,\"bitable\":false}";
    final JsonParser parser = Json.createParser(new StringReader(result));
    String key = null;
    String value = null;
    while (parser.hasNext()) {
        final Event event = parser.next();
        switch (event) {
        case KEY_NAME:
            key = parser.getString();
            System.out.println(key);
            break;
        case VALUE_STRING:
            value = parser.getString();
            System.out.println(value);
            break;
        }
    }
    parser.close();
}

The JSON representation

{
    "name": "Falco",
    "age": 3,
    "bitable": false
}