Java Json 漂亮的打印 javax.json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23007567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 19:59:33  来源:igfitidea点击:

Java Json pretty print javax.json

javajson

提问by ChrisGeo

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

我正在尝试使用 javax.json API 漂亮地打印 json

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)

采纳答案by David

You should be using JsonWriter instead of JsonGenerator.

您应该使用 JsonWriter 而不是 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();

回答by Philip Durbin

Here's a solution for pretty printing (indenting) JSON with javax.jsonand javax.ws.rsusing Jersey:

这里有一个漂亮的印刷(缩进)JSON一个解决方案javax.json,并javax.ws.rs利用球衣号码:

@GET
@Path("stuff")
public Response getStuff(@QueryParam("pretty") boolean pretty) {
    JsonArrayBuilder stuff = Json.createArrayBuilder().add("foo").add("bar");
    JsonObject jsonObject = Json.createObjectBuilder()
            .add("status", "OK")
            .add("data", stuff).build();
    if (pretty) {
        Map<String, Boolean> config = new HashMap<>();
        config.put(JsonGenerator.PRETTY_PRINTING, true);
        JsonWriterFactory jwf = Json.createWriterFactory(config);
        StringWriter sw = new StringWriter();
        try (JsonWriter jsonWriter = jwf.createWriter(sw)) {
            jsonWriter.writeObject(jsonObject);
        }
        // return "Content-Type: application/json", not "text/plain"
        MediaType mediaType = MediaType.APPLICATION_JSON_TYPE;
        return Response.ok(sw.toString(), mediaType).build();
    } else {
        return Response.ok(jsonObject).build();
    }

}

Sample curloutput:

示例curl输出:

$ curl -i http://localhost:8080/api/stuff?pretty=true
HTTP/1.1 200 OK
Content-Type: application/json
Date: Fri, 08 Aug 2014 14:32:40 GMT
Content-Length: 71


{
    "status":"OK",
    "data":[
        "foo",
        "bar"
    ]
} 
$ curl http://localhost:8080/api/stuff
{"status":"OK","data":["foo","bar"]}

See also:

也可以看看:

回答by Mr. Polywhirl

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

您可以通过使用JsonWriterFactory. 这需要一个属性的配置映射。

Use the JsonWriterto write to the StringWriter.

使用JsonWriter写入StringWriter.

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

我添加了一个方便的方法,它已经PRETTY_PRINTING为您传递了标志。

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;
}