我使用JSON -simple,我需要漂亮地打印JSON数据(使其更易于阅读)。

我还没能在那个库中找到这个功能。 这通常是如何实现的?


当前回答

如果您正在使用用于JSON处理(JSR-353)实现的Java API,那么您可以指定JsonGenerator。当您创建JsonGeneratorFactory时,PRETTY_PRINTING属性。

下面的例子最初发表在我的博客文章中。

import java.util.*;
import javax.json.Json;
import javax.json.stream.*;

Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JsonGenerator.PRETTY_PRINTING, true);
JsonGeneratorFactory jgf = Json.createGeneratorFactory(properties);
JsonGenerator jg = jgf.createGenerator(System.out);

jg.writeStartObject()                    // {
    .write("name", "Jane Doe")           //    "name":"Jane Doe",
    .writeStartObject("address")         //    "address":{
        .write("type", 1)                //        "type":1,
        .write("street", "1 A Street")   //        "street":"1 A Street",
        .writeNull("city")               //        "city":null,
        .write("verified", false)        //        "verified":false
    .writeEnd()                          //    },
    .writeStartArray("phone-numbers")    //    "phone-numbers":[
        .writeStartObject()              //        {
            .write("number", "555-1111") //            "number":"555-1111",
            .write("extension", "123")   //            "extension":"123"
        .writeEnd()                      //        },
        .writeStartObject()              //        {
            .write("number", "555-2222") //            "number":"555-2222",
            .writeNull("extension")      //            "extension":null
        .writeEnd()                      //        }
    .writeEnd()                          //    ]
.writeEnd()                              // }
.close();

其他回答

这招对我很管用,用了杰克逊的话:

mapper.writerWithDefaultPrettyPrinter().writeValueAsString(JSONString)

如果您正在使用用于JSON处理(JSR-353)实现的Java API,那么您可以指定JsonGenerator。当您创建JsonGeneratorFactory时,PRETTY_PRINTING属性。

下面的例子最初发表在我的博客文章中。

import java.util.*;
import javax.json.Json;
import javax.json.stream.*;

Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JsonGenerator.PRETTY_PRINTING, true);
JsonGeneratorFactory jgf = Json.createGeneratorFactory(properties);
JsonGenerator jg = jgf.createGenerator(System.out);

jg.writeStartObject()                    // {
    .write("name", "Jane Doe")           //    "name":"Jane Doe",
    .writeStartObject("address")         //    "address":{
        .write("type", 1)                //        "type":1,
        .write("street", "1 A Street")   //        "street":"1 A Street",
        .writeNull("city")               //        "city":null,
        .write("verified", false)        //        "verified":false
    .writeEnd()                          //    },
    .writeStartArray("phone-numbers")    //    "phone-numbers":[
        .writeStartObject()              //        {
            .write("number", "555-1111") //            "number":"555-1111",
            .write("extension", "123")   //            "extension":"123"
        .writeEnd()                      //        },
        .writeStartObject()              //        {
            .write("number", "555-2222") //            "number":"555-2222",
            .writeNull("extension")      //            "extension":null
        .writeEnd()                      //        }
    .writeEnd()                          //    ]
.writeEnd()                              // }
.close();

I also use the org.json.simple package. I have simply coded the formatter, but since I don't have nulls, numbers or booleans in my JSON objects in the program that I wrote, I only coded for strings, objects and arrays. If anyone is interested, let this just be in the public domain. You are welcome to add the missing data types (where it says in the comment "it's a string"). Also, you can add the indentation as a parameter whereas mine is just two spaces. Please reshare after you've tested your improvements.

用法: printJsonObject(jsonObject, “”);

功能:

    public static void printJsonObject(JSONObject object, String prefix) {
        boolean notFirst = false;
        System.out.println(prefix + "{");
        for (Object key : object.keySet()) {
            if (notFirst) {
                System.out.println(", ");
            }
            notFirst = true;
            Object value = object.get(key);
            System.out.print(prefix + "  " + "\"" + key + "\"" + ": ");
            if (value instanceof JSONObject) {
                printJsonObject((JSONObject) value, prefix + "  ");
            } else if (value instanceof JSONArray) {
                printJsonArray((JSONArray) value, prefix + "  ");
            } else {  // it's a string
                System.out.print("\"" + value + "\"");
            }
        }
        System.out.println("");
        System.out.print(prefix + "}");
    }

    public static void printJsonArray(JSONArray array, String prefix) {
        boolean notFirst = false;
        System.out.println("[");
        for (Object item : array) {
            if (notFirst) {
                System.out.println(", ");
            }
            notFirst = true;
            if (item instanceof JSONObject) {
                printJsonObject((JSONObject) item, prefix + "  ");
            } else if (item instanceof JSONArray) {
                printJsonArray((JSONArray) item, prefix + "  ");
            } else {
                System.out.print(prefix + "  " + "\"" + item + "\"");
            }
        }
        System.out.println("");
        System.out.print(prefix + "]");
    }

漂亮的打印与GSON一行:

System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().parse(jsonString)));

除了内联之外,这等价于已接受的答案。

在JSONLib中,你可以这样使用:

String jsonTxt = JSONUtils.valueToString(json, 8, 4);

来自Javadoc: