Prettify JSON in 4 lines with JSON-P


JSon Processing API was a great step for standardization of JSON in Java world and its API is surprisingly smooth to prettify a JSon payload.

Before showing you how to do so let keep in mind the JVM provides nice String bridges to streams aka StringReader and StringWriter so instead of using an InputStream of an OutputStream you can use the method with Reader/Writer as parameter in next sample and it will work the same :).

So how to prettify a stream with JSON-P? The idea is actually easy: while reading the stream just output it to a prettify writer.

Reading an json object is just a matter of creating a json reader then you can get a JSonStructure. Writing a JSonStructure is just a matter of creating a json writer and passing the structure to the write method. Finally prettifying an output is just a matter of setting javax.json.stream.JsonGenerator.prettyPrinting property of the writer to true :). Think we have all we need to prettify a stream:

final JsonProvider provider = JsonProvider.provider(); // doesnt need to be instantiated each time
try (final JsonReader reader = provider.createReaderFactory(emptyMap()).createReader(in)) {
    try (final JsonWriter writer = provider.createWriterFactory(singletonMap("javax.json.stream.JsonGenerator.prettyPrinting", "true")).createWriter(out)) {
        writer.write(reader.read());
    }
}

Note: of course you can use Json.createReader method but then you have no more guarantee the framework can optimize your operations so better to go through factories in general.

Simple and powerful! Wrap this code in a small main reading System.in and you can now pipe any json to prettify it:

wget http://somejson.com.the.json -O - | java -jar myjsonprettifier.jar

🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s