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

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


当前回答

遵循JSON-P 1.0规范(JSR-353),对于给定的JsonStructure (JsonObject或JsonArray),一个更当前的解决方案可能是这样的:

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.json.Json;
import javax.json.JsonStructure;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;

public class PrettyJson {

    private static JsonWriterFactory FACTORY_INSTANCE;

    public static String toString(final JsonStructure status) {

        final StringWriter stringWriter = new StringWriter();

        final JsonWriter jsonWriter = getPrettyJsonWriterFactory()
                .createWriter(stringWriter);

        jsonWriter.write(status);
        jsonWriter.close();

        return stringWriter.toString();
    }

    private static JsonWriterFactory getPrettyJsonWriterFactory() {
        if (null == FACTORY_INSTANCE) {
            final Map<String, Object> properties = new HashMap<>(1);
            properties.put(JsonGenerator.PRETTY_PRINTING, true);
            FACTORY_INSTANCE = Json.createWriterFactory(properties);
        }
        return FACTORY_INSTANCE;
    }

}

其他回答

现在这可以通过JSONLib库实现:

http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html

当(且仅当)你使用重载的toString(int indentationFactor)方法而不是标准的toString()方法。

我已经在以下版本的API上验证了这一点:

<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20140107</version>
</dependency>

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

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

来自Javadoc:

与杰克逊(com.fasterxml.jackson.databind):

ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject))

如何启用漂亮的JSON打印输出(Jackson)

我知道这已经在答案中,但我想在这里单独写它,因为很可能您已经将Jackson作为依赖项,因此您需要的只是额外的一行代码

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 + "]");
    }

你可以使用小的json库

String jsonstring = ....;
JsonValue json = JsonParser.parse(jsonstring);
String jsonIndendedByTwoSpaces = json.toPrettyString("  ");