Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Json pretty print javax.json

Tags:

java

json

I'm trying to pretty print json with the javax.json API

The code I'm currently using is as follows:

private String prettyPrint(String json) {
        StringWriter sw = new StringWriter();

        try {
            JsonReader jr = Json.createReader(new StringReader(json));

            JsonObject jobj = jr.readObject();



            Map<String, Object> properties = new HashMap<>(1);
            properties.put(JsonGenerator.PRETTY_PRINTING, true);


            JsonGeneratorFactory jf = Json.createGeneratorFactory(properties);
            JsonGenerator jg = jf.createGenerator(sw);

            jg.write(jobj).close();


        } catch (Exception e) {
        }

        String prettyPrinted = sw.toString();

        return prettyPrinted;
    }

I'm getting the following exception:

11:47:08,830 ERROR [stderr] (EJB default - 1) javax.json.stream.JsonGenerationException: write(JsonValue) can only be called in array context
11:47:08,835 ERROR [stderr] (EJB default - 1)   at org.glassfish.json.JsonGeneratorImpl.write(JsonGeneratorImpl.java:301)
11:47:08,838 ERROR [stderr] (EJB default - 1)   at org.glassfish.json.JsonPrettyGeneratorImpl.write(JsonPrettyGeneratorImpl.java:55)
11:47:08,841 ERROR [stderr] (EJB default - 1)   at org.proactive.rest.VideoFeedService.prettyPrint(VideoFeedService.java:247)
11:47:08,843 ERROR [stderr] (EJB default - 1)   at org.proactive.rest.VideoFeedService.requestVideoFeedData(VideoFeedService.java:124)
11:47:08,845 ERROR [stderr] (EJB default - 1)   at org.proactive.rest.VideoFeedService.run(VideoFeedService.java:86)
11:47:08,848 ERROR [stderr] (EJB default - 1)   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
11:47:08,850 ERROR [stderr] (EJB default - 1)   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
11:47:08,852 ERROR [stderr] (EJB default - 1)   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
11:47:08,854 ERROR [stderr] (EJB default - 1)   at java.lang.reflect.Method.invoke(Method.java:483)
like image 920
ChrisGeo Avatar asked Apr 11 '14 08:04

ChrisGeo


People also ask

How do I pretty print a JSON object?

Use json. dumps() method to prettyprint JSON properly by specifying indent and separators. The json. dumps() method returns prettyprinted JSON data in string format.

What is pretty print in Java?

Prettyprint is the process of converting and presenting source code or other objects in a legible and attractive way. A prettyprinter takes blocks of code and prints them in an aesthetically pleasing fashion, presenting the characters with line breaks and indentations to make the code comprehensible.

Can we print JSON object in Java?

We can pretty-print a JSON using the toString(int indentFactor) method of org. json. JSONObject class, where indentFactor is the number of spaces to add to each level of indentation.

What is JSON object class in Java?

JsonObject class represents an immutable JSON object value (an unordered collection of zero or more name/value pairs). It also provides unmodifiable map view to the JSON object name/value mappings. A JsonObject instance can be created from an input source using JsonReader.


2 Answers

You should be using JsonWriter instead of JsonGenerator.

Replace these lines:

JsonGeneratorFactory jf = Json.createGeneratorFactory(properties);
JsonGenerator jg = jf.createGenerator(sw);

jg.write(jobj).close();

with these:

JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
JsonWriter jsonWriter = writerFactory.createWriter(sw);

jsonWriter.writeObject(jobj);
jsonWriter.close();
like image 55
David Avatar answered Sep 22 '22 14:09

David


You can achieve pretty printing by utilizing the JsonWriterFactory. This takes a configuration map of properties.

Use the JsonWriter to write to the StringWriter.

I added a convenience method which already passes the PRETTY_PRINTING flag for you.

public static String prettyPrint(JsonStructure json) {
    return jsonFormat(json, JsonGenerator.PRETTY_PRINTING);
}

public static String jsonFormat(JsonStructure json, String... options) {
    StringWriter stringWriter = new StringWriter();
    Map<String, Boolean> config = buildConfig(options);
    JsonWriterFactory writerFactory = Json.createWriterFactory(config);
    JsonWriter jsonWriter = writerFactory.createWriter(stringWriter);

    jsonWriter.write(json);
    jsonWriter.close();

    return stringWriter.toString();
}

private static Map<String, Boolean> buildConfig(String... options) {
    Map<String, Boolean> config = new HashMap<String, Boolean>();

    if (options != null) {
        for (String option : options) {
            config.put(option, true);
        }
    }

    return config;
}
like image 27
Mr. Polywhirl Avatar answered Sep 22 '22 14:09

Mr. Polywhirl