A short document about simple manipulation of JSON using the Java API for JSON Processing 1.1. (See also JSON-B for (de-)serialization; https://developer.ibm.com/articles/j-javaee8-json-binding-4/ (and https://www.e4developer.com/2018/03/04/introducing-json-b-with-spring-boot-2-0/).)
If you use Java SE, you need to add the javax JSON API to your dependencies.
Specify dependencies in your
pom.xml
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1</version>
</dependency>
If you use Java EE, this is already provided by your application server.
You may now use the API. Check json.org for a good explanation of JSON notation, and here for a good tutorial and introduction to JSON manipulation in Java.
Obtain a json object from a String
public JsonObject asJson(String data) {
JsonObject json;
try (JsonReader jr = Json.createReader(new StringReader(data))) {
json = jr.readObject();
}
return json;
}
This example uses the try-with-resources syntax.
Pretty print a json value
public String asPrettyString(JsonValue json) {
StringWriter stringWriter = new StringWriter();
JsonWriterFactory writerFactory = Json.createWriterFactory(ImmutableMap.of(JsonGenerator.PRETTY_PRINTING, true));
try (JsonWriter jsonWriter = writerFactory.createWriter(stringWriter)) {
jsonWriter.write(json);
}
return stringWriter.toString();
}