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

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


当前回答

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

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

来自Javadoc:

其他回答

现在这可以通过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>

大多数现有的答案要么依赖于一些外部库,要么需要一个特殊的Java版本。下面是一个简单的代码来漂亮地打印一个JSON字符串,只使用一般的Java api(在Java 7中更高;虽然还没有尝试过旧版本)。

基本思想是基于JSON中的特殊字符来调整格式。例如,如果观察到'{'或'[',代码将创建一个新行并增加缩进级别。

免责声明:我只测试了一些简单的JSON情况(基本的键值对,列表,嵌套JSON),所以它可能需要一些工作更一般的JSON文本,如字符串值内引号,或特殊字符(\n, \t等)。

/**
 * A simple implementation to pretty-print JSON file.
 *
 * @param unformattedJsonString
 * @return
 */
public static String prettyPrintJSON(String unformattedJsonString) {
  StringBuilder prettyJSONBuilder = new StringBuilder();
  int indentLevel = 0;
  boolean inQuote = false;
  for(char charFromUnformattedJson : unformattedJsonString.toCharArray()) {
    switch(charFromUnformattedJson) {
      case '"':
        // switch the quoting status
        inQuote = !inQuote;
        prettyJSONBuilder.append(charFromUnformattedJson);
        break;
      case ' ':
        // For space: ignore the space if it is not being quoted.
        if(inQuote) {
          prettyJSONBuilder.append(charFromUnformattedJson);
        }
        break;
      case '{':
      case '[':
        // Starting a new block: increase the indent level
        prettyJSONBuilder.append(charFromUnformattedJson);
        indentLevel++;
        appendIndentedNewLine(indentLevel, prettyJSONBuilder);
        break;
      case '}':
      case ']':
        // Ending a new block; decrese the indent level
        indentLevel--;
        appendIndentedNewLine(indentLevel, prettyJSONBuilder);
        prettyJSONBuilder.append(charFromUnformattedJson);
        break;
      case ',':
        // Ending a json item; create a new line after
        prettyJSONBuilder.append(charFromUnformattedJson);
        if(!inQuote) {
          appendIndentedNewLine(indentLevel, prettyJSONBuilder);
        }
        break;
      default:
        prettyJSONBuilder.append(charFromUnformattedJson);
    }
  }
  return prettyJSONBuilder.toString();
}

/**
 * Print a new line with indention at the beginning of the new line.
 * @param indentLevel
 * @param stringBuilder
 */
private static void appendIndentedNewLine(int indentLevel, StringBuilder stringBuilder) {
  stringBuilder.append("\n");
  for(int i = 0; i < indentLevel; i++) {
    // Assuming indention using 2 spaces
    stringBuilder.append("  ");
  }
}

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

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

来自Javadoc:

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似乎支持这一点,尽管我不知道您是否想从正在使用的库切换。

来自用户指南:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);