This is a quick Getting Started guide showcasing the basic JSON-P operations.
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1</version>
</dependency>
The main JSON-P entry point is the Json
class. It provides all necessary methods to parse and
build JSON strings from Java. Json
is a singleton containing static factory methods for all relevant elements of the JSON-P API.
// Create Json and print
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);
// Read back
JsonReader jsonReader = Json.createReader(new StringReader("{\"name\":\"Falco\",\"age\":3,\"bitable\":false}"));
JsonObject jobj = jsonReader.readObject();
System.out.println(jobj);
// Output
{"name":"Falco","age":3,"biteable":false}
{"name":"Falco","age":3,"bitable":false}
The Streaming API of JSON-P supports parsing a JSON string. Unlike the Object model this offers more generic access to JSON strings that may change more often with attributes added or similar structural changes. Streaming API is also the preferred method for very large JSON strings that could take more memory reading them altogether through the Object model API.
// 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:
String string = parser.getString();
System.out.println(string);
break;
case VALUE_NUMBER:
BigDecimal number = parser.getBigDecimal();
System.out.println(number);
break;
case VALUE_TRUE:
System.out.println(true);
break;
case VALUE_FALSE:
System.out.println(false);
break;
}
}
parser.close();
}
// Output
name
Falco
age
3
bitable
false