Java 中的漂亮打印 JSON

发布于 2024-09-30 17:59:10 字数 198 浏览 7 评论 0原文

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

我无法在该库中找到此功能。 这通常是如何实现的?

I'm using and I need to pretty-print JSON data (make it more human readable).

I haven't been able to find this functionality within that library.
How is this commonly achieved?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

冷弦 2024-10-07 17:59:11

我使用 org.json 内置方法来漂亮地打印数据。

import org.json.JSONObject;
JSONObject json = new JSONObject(jsonString); // Convert text to object
System.out.println(json.toString(4)); // Print it with specified indentation

JSON 中字段的顺序根据定义是随机的。具体顺序取决于解析器的实现。

I used org.json built-in methods to pretty-print the data.

import org.json.JSONObject;
JSONObject json = new JSONObject(jsonString); // Convert text to object
System.out.println(json.toString(4)); // Print it with specified indentation

The order of fields in JSON is random per definition. A specific order is subject to parser implementation.

生活了然无味 2024-10-07 17:59:11

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

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

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

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

With Jackson (com.fasterxml.jackson.databind):

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

From: How to enable pretty print JSON output (Jackson)

I know this is already in the answers, but I want to write it separately here because chances are, you already have Jackson as a dependency and so all you will need would be an extra line of code

原来分手还会想你 2024-10-07 17:59:11

似乎 GSON 支持这一点,尽管我不知道你是否想从你所在的库切换使用。

来自用户指南:

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

It seems like GSON supports this, although I don't know if you want to switch from the library you are using.

From the user guide:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);
欢烬 2024-10-07 17:59:11

使用组织 json。参考链接

JSONObject jsonObject = new JSONObject(obj);
String prettyJson = jsonObject.toString(4);

使用格森。参考链接

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(obj);

使用 Jackson。参考链接

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(obj);

使用 Genson。参考链接

Genson prettyGenson = new GensonBuilder().useIndentation(true).create();
String prettyJson = prettyGenson.serialize(obj);

使用 javax.json。参考链接

Map<String, Boolean> config = new HashMap<>();

config.put(JsonGenerator.PRETTY_PRINTING, true);

JsonWriterFactory writerFactory = Json.createWriterFactory(config);
Writer writer = new StringWriter();

writerFactory.createWriter(writer).write(jsonObject);

String json = writer.toString();

使用 Moshi 库。参考链接

String json = jsonAdapter.indent("  ").toJson(emp1);

(或者)

Buffer buffer = new Buffer();
JsonWriter jsonWriter = JsonWriter.of(buffer);
jsonWriter.setIndent("   ");

jsonAdapter.toJson(jsonWriter, emp1);

json = buffer.readUtf8();

Using org json. Reference link

JSONObject jsonObject = new JSONObject(obj);
String prettyJson = jsonObject.toString(4);

Using Gson. Reference link

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(obj);

Using Jackson. Reference link

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(obj);

Using Genson. Reference link.

Genson prettyGenson = new GensonBuilder().useIndentation(true).create();
String prettyJson = prettyGenson.serialize(obj);

Using javax.json. Reference link.

Map<String, Boolean> config = new HashMap<>();

config.put(JsonGenerator.PRETTY_PRINTING, true);

JsonWriterFactory writerFactory = Json.createWriterFactory(config);
Writer writer = new StringWriter();

writerFactory.createWriter(writer).write(jsonObject);

String json = writer.toString();

Using Moshi library. Reference link.

String json = jsonAdapter.indent("  ").toJson(emp1);

(OR)

Buffer buffer = new Buffer();
JsonWriter jsonWriter = JsonWriter.of(buffer);
jsonWriter.setIndent("   ");

jsonAdapter.toJson(jsonWriter, emp1);

json = buffer.readUtf8();
时光清浅 2024-10-07 17:59:11

如果您使用 Java API 进行 JSON 处理 (JSR-353) 实现,则可以在创建 JsonGeneratorFactory 时指定 JsonGenerator.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();

If you are using a Java API for JSON Processing (JSR-353) implementation then you can specify the JsonGenerator.PRETTY_PRINTING property when you create a JsonGeneratorFactory.

The following example has been originally published on my blog post.

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();
壹場煙雨 2024-10-07 17:59:11

在一行中使用 GSON 进行漂亮的打印:

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

除了内联之外,这相当于 接受的答案

Pretty printing with GSON in one line:

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

Besides inlining, this is equivalent to the accepted answer.

做个少女永远怀春 2024-10-07 17:59:11

大多数现有答案要么依赖于某些外部库,要么需要特殊的 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("  ");
  }
}

Most of the existing answers either depend on some external library, or requiring a special Java version. Here is a simple code to pretty print a JSON string, only using general Java APIs (available in Java 7 for higher; haven't tried older version although).

The basic idea is to tigger the formatting based on special characters in JSON. For example, if a '{' or '[' is observed, the code will create a new line and increase the indent level.

Disclaimer: I only tested this for some simple JSON cases (basic key-value pair, list, nested JSON) so it may need some work for more general JSON text, like string value with quotes inside, or special characters (\n, \t etc.).

/**
 * 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("  ");
  }
}
习ぎ惯性依靠 2024-10-07 17:59:11

我的情况是我的项目使用旧版(非 JSR)JSON 解析器,不支持漂亮的打印。然而,我需要生成打印精美的 JSON 样本;只要您使用 Java 7 到 Java 14,就可以无需添加任何额外的库:

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine scriptEngine = manager.getEngineByName("JavaScript");
scriptEngine.put("jsonString", jsonStringNoWhitespace);
scriptEngine.eval("result = JSON.stringify(JSON.parse(jsonString), null, 2)");
String prettyPrintedJson = (String) scriptEngine.get("result");

My situation is my project uses a legacy (non-JSR) JSON parser that does not support pretty printing. However, I needed to produce pretty-printed JSON samples; this is possible without having to add any extra libraries as long as you are using Java 7 till Java 14:

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine scriptEngine = manager.getEngineByName("JavaScript");
scriptEngine.put("jsonString", jsonStringNoWhitespace);
scriptEngine.eval("result = JSON.stringify(JSON.parse(jsonString), null, 2)");
String prettyPrintedJson = (String) scriptEngine.get("result");
甜味拾荒者 2024-10-07 17:59:11

现在可以使用 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>

Now this can be achieved with the JSONLib library:

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

If (and only if) you use the overloaded toString(int indentationFactor) method and not the standard toString() method.

I have verified this on the following version of the API:

<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20140107</version>
</dependency>
独﹏钓一江月 2024-10-07 17:59:11

遵循 JSON-P 1.0 规范 (JSR-353) 的更新解决方案给定的 JsonStructureJsonObjectJsonArray)可能如下所示:

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

}

Following the JSON-P 1.0 specs (JSR-353) a more current solution for a given JsonStructure (JsonObject or JsonArray) could look like this:

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

}
幼儿园老大 2024-10-07 17:59:11

在 JSONLib 中,您可以使用它:

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

来自 Javadoc:

In JSONLib you can use this:

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

From the Javadoc:

楠木可依 2024-10-07 17:59:11

您可以像下面一样使用 Gson

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonString = gson.toJson(object);

从帖子 JSON Pretty使用 Gson 打印

或者,您可以像下面一样使用 Jackson

ObjectMapper mapper = new ObjectMapper();
String perttyStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);

从帖子 Java 中漂亮的打印 JSON (Jackson)

希望有帮助!

You can use Gson like below

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonString = gson.toJson(object);

From the post JSON pretty print using Gson

Alternatively, You can use Jackson like below

ObjectMapper mapper = new ObjectMapper();
String perttyStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);

From the post Pretty print JSON in Java (Jackson)

Hope this help!

甜中书 2024-10-07 17:59:11

这对我有用,使用杰克逊:

mapper.writerWithDefaultPrettyPrinter().writeValueAsString(JSONString)

This worked for me, using Jackson:

mapper.writerWithDefaultPrettyPrinter().writeValueAsString(JSONString)
眼泪也成诗 2024-10-07 17:59:11

更新:new JsonParser().parse(...) is @deprecated


基于Gson 2.8.6的javadoc:

无需实例化此类,而是使用静态方法。

JsonParser 静态方法:

JsonParser.parseString​(jsonString);
JsonParser.parseReader​(reader);

包:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;

示例:

private Gson GSON = new GsonBuilder().setPrettyPrinting().create();
public static String getPerfectJSON(String unformattedJSON) {
    String perfectJSON = GSON.toJson(JsonParser.parseString(unformattedJSON));
    return perfectJSON;
}

使用 Maven 的 Google Gson 依赖项:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.6</version>
</dependency>

参考:

Update: new JsonParser().parse(...) is @deprecated


Based on the javadoc for Gson 2.8.6:

No need to instantiate this class, use the static methods instead.

JsonParser static methods:

JsonParser.parseString​(jsonString);
JsonParser.parseReader​(reader);

Packages:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;

Example:

private Gson GSON = new GsonBuilder().setPrettyPrinting().create();
public static String getPerfectJSON(String unformattedJSON) {
    String perfectJSON = GSON.toJson(JsonParser.parseString(unformattedJSON));
    return perfectJSON;
}

Google Gson dependency using Maven:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.6</version>
</dependency>

Reference:

悲歌长辞 2024-10-07 17:59:11

所以我也喜欢 json-simple 库,并研究了如何漂亮地打印它的输出。不幸的是,虽然这是一个 开放问题,但我找不到任何代码为了它。所以我想我应该尝试一下,这就是我想出的(使用他们自己的源代码)..

public class JsonPrinter {
  
  
  
  public static String toJson(Map<?,?> map) {
    StringBuilder out = new StringBuilder(32);
    new JsonPrinter(out).print(map);
    return out.toString();
  }
  
  
  public static String toJson(List<?> list) {
    StringBuilder out = new StringBuilder(32);
    new JsonPrinter(out).print(list);
    return out.toString();
  }
  
  
  
  
  
  
  
  private final Appendable out;
  private final String indentUnit;
  private final String newLine;
  
  
  private int indents;
  
  public JsonPrinter(Appendable out) {
    this(out, "  ", System.lineSeparator());
  }

  /**
   * 
   */
  public JsonPrinter(Appendable out, String indentUnit, String newLine) {
    this.out = Objects.requireNonNull(out, "null out");
    this.indentUnit = Objects.requireNonNull(indentUnit, "null indentUnit");
    this.newLine = Objects.requireNonNull(newLine, "null newLine");
    
    if (!indentUnit.isBlank())
      throw new IllegalArgumentException(
          "indentUnit must be a blank sequence (quoted): '" + indentUnit + "'");
    if (!"\r\n".equals(newLine) && ! "\n".equals(newLine))
      throw new IllegalArgumentException(
          "unrecognized newLine (quoted): '" + newLine + "'");
  }
  
  
  public void print(List<?> list) throws UncheckedIOException {
    try {
      assert indents == 0;
      printImpl(list);
      assert indents == 0;
    } catch (IOException iox) {
      throw new UncheckedIOException("on print(List): " + list, iox);
    }
  }
  
  
  public void print(Map<?,?> map) throws UncheckedIOException {
    try {
      assert indents == 0;
      printImpl(map);
      assert indents == 0;
    } catch (IOException iox) {
      throw new UncheckedIOException("on print(Map): " + map, iox);
    }
  }
  
  
  protected void printImpl(List<?> list) throws IOException {
    if (list == null) {
      out.append("null");
      return;
    }
    
    
    boolean first = true;
    var iter = list.iterator();
    
    open('[');
    while (iter.hasNext()) {
      if (first)
        first = false;
      else
        out.append(',');
      
      out.append(newLine);
      appendIndents();
      
      appendValue(iter.next());
    }
    close(']');
  }
  
  
  protected void printImpl(Map<?, ?> map) throws IOException {
    if (map == null) {
      out.append("null");
      return;
    }
    
    
    boolean first = true;
    var iter = map.entrySet().iterator();
    
    open('{');
    while (iter.hasNext()) {
      if (first)
        first = false;
      else
        out.append(',');
      
      out.append(newLine);
      appendIndents();
      
      var entry = iter.next();
      print(entry.getKey().toString(), entry.getValue());
    }
    close('}');
  }
  
  
  private void open(char c) throws IOException {
    out.append(c);
    ++indents;
  }
  
  private void close(char c) throws IOException {
    --indents;
    out.append(newLine);
    appendIndents();
    out.append(c);
  }
  
  private void appendIndents() throws IOException {
    for (int count = indents; count-- > 0; )
      out.append(indentUnit);
  }
  
  
  
  private void print(String key, Object value) throws IOException {
    out.append('"');
    appendString(key);
    out.append('"').append(':').append(' ');
    appendValue(value);
  }
  
  
  
  private void appendString(String s) throws IOException {
    for (int i = 0; i < s.length(); i++) {
      char ch = s.charAt(i);
      switch(ch){
      case '"':
        out.append("\\\"");
        break;
      case '\\':
        out.append("\\\\");
        break;
      case '\b':
        out.append("\\b");
        break;
      case '\f':
        out.append("\\f");
        break;
      case '\n':
        out.append("\\n");
        break;
      case '\r':
        out.append("\\r");
        break;
      case '\t':
        out.append("\\t");
        break;
      case '/':
        out.append("\\/");
        break;
      default:
                //Reference: http://www.unicode.org/versions/Unicode5.1.0/
        if ((ch>='\u0000' && ch<='\u001F') || (ch>='\u007F' && ch<='\u009F') || (ch>='\u2000' && ch<='\u20FF')) {
          String ss = Integer.toHexString(ch);
          out.append("\\u");
          for (int k=0; k < 4-ss.length(); k++) {
            out.append('0');
          }
          out.append(ss.toUpperCase());
        }
        else{
          out.append(ch);
        }
      }
    }//for
  }
  
  
  private void appendValue(Object value) throws IOException {
    if (value == null) {
      out.append("null");
      
    } else if (value instanceof String) {
      out.append('"');
      appendString(value.toString());
      out.append('"');
      
    } else if (value instanceof Double) {
      var num = (Double) value;
      if (num.isInfinite() || num.isNaN())
        out.append("null");
      else
        out.append(value.toString());
      
    } else if (value instanceof Float) {
      var num = (Float) value;
      if (num.isInfinite() || num.isNaN())
        out.append("null");
      else
        out.append(value.toString());
      
    } else if (value instanceof Map) {
      printImpl((Map<?,?>) value);
      
    } else if (value instanceof List) {
      printImpl((List<?>) value);
      
//    } else if (value instanceof Number || value instanceof Boolean) {
//      out.append(value.toString());
      
    } else {
      out.append(value.toString());
      
    }
  }

}

它适用于 JSONObjectJSONArray 即使它没有依赖于它们..因为这些是常规的 MapList 对象。 (事实上代码是从同一个库中提取的)。

https://github.com/crums-io/io-util/blob/master/src/main/java/io/crums/util/json/JsonPrinter.java

So I too like the json-simple lib, and looked into pretty printing its output. Unfortunately, while it's an open issue there, I couldn't find any code for it. So I thought I'd give it a try, here's what I came up with (using their own source)..

public class JsonPrinter {
  
  
  
  public static String toJson(Map<?,?> map) {
    StringBuilder out = new StringBuilder(32);
    new JsonPrinter(out).print(map);
    return out.toString();
  }
  
  
  public static String toJson(List<?> list) {
    StringBuilder out = new StringBuilder(32);
    new JsonPrinter(out).print(list);
    return out.toString();
  }
  
  
  
  
  
  
  
  private final Appendable out;
  private final String indentUnit;
  private final String newLine;
  
  
  private int indents;
  
  public JsonPrinter(Appendable out) {
    this(out, "  ", System.lineSeparator());
  }

  /**
   * 
   */
  public JsonPrinter(Appendable out, String indentUnit, String newLine) {
    this.out = Objects.requireNonNull(out, "null out");
    this.indentUnit = Objects.requireNonNull(indentUnit, "null indentUnit");
    this.newLine = Objects.requireNonNull(newLine, "null newLine");
    
    if (!indentUnit.isBlank())
      throw new IllegalArgumentException(
          "indentUnit must be a blank sequence (quoted): '" + indentUnit + "'");
    if (!"\r\n".equals(newLine) && ! "\n".equals(newLine))
      throw new IllegalArgumentException(
          "unrecognized newLine (quoted): '" + newLine + "'");
  }
  
  
  public void print(List<?> list) throws UncheckedIOException {
    try {
      assert indents == 0;
      printImpl(list);
      assert indents == 0;
    } catch (IOException iox) {
      throw new UncheckedIOException("on print(List): " + list, iox);
    }
  }
  
  
  public void print(Map<?,?> map) throws UncheckedIOException {
    try {
      assert indents == 0;
      printImpl(map);
      assert indents == 0;
    } catch (IOException iox) {
      throw new UncheckedIOException("on print(Map): " + map, iox);
    }
  }
  
  
  protected void printImpl(List<?> list) throws IOException {
    if (list == null) {
      out.append("null");
      return;
    }
    
    
    boolean first = true;
    var iter = list.iterator();
    
    open('[');
    while (iter.hasNext()) {
      if (first)
        first = false;
      else
        out.append(',');
      
      out.append(newLine);
      appendIndents();
      
      appendValue(iter.next());
    }
    close(']');
  }
  
  
  protected void printImpl(Map<?, ?> map) throws IOException {
    if (map == null) {
      out.append("null");
      return;
    }
    
    
    boolean first = true;
    var iter = map.entrySet().iterator();
    
    open('{');
    while (iter.hasNext()) {
      if (first)
        first = false;
      else
        out.append(',');
      
      out.append(newLine);
      appendIndents();
      
      var entry = iter.next();
      print(entry.getKey().toString(), entry.getValue());
    }
    close('}');
  }
  
  
  private void open(char c) throws IOException {
    out.append(c);
    ++indents;
  }
  
  private void close(char c) throws IOException {
    --indents;
    out.append(newLine);
    appendIndents();
    out.append(c);
  }
  
  private void appendIndents() throws IOException {
    for (int count = indents; count-- > 0; )
      out.append(indentUnit);
  }
  
  
  
  private void print(String key, Object value) throws IOException {
    out.append('"');
    appendString(key);
    out.append('"').append(':').append(' ');
    appendValue(value);
  }
  
  
  
  private void appendString(String s) throws IOException {
    for (int i = 0; i < s.length(); i++) {
      char ch = s.charAt(i);
      switch(ch){
      case '"':
        out.append("\\\"");
        break;
      case '\\':
        out.append("\\\\");
        break;
      case '\b':
        out.append("\\b");
        break;
      case '\f':
        out.append("\\f");
        break;
      case '\n':
        out.append("\\n");
        break;
      case '\r':
        out.append("\\r");
        break;
      case '\t':
        out.append("\\t");
        break;
      case '/':
        out.append("\\/");
        break;
      default:
                //Reference: http://www.unicode.org/versions/Unicode5.1.0/
        if ((ch>='\u0000' && ch<='\u001F') || (ch>='\u007F' && ch<='\u009F') || (ch>='\u2000' && ch<='\u20FF')) {
          String ss = Integer.toHexString(ch);
          out.append("\\u");
          for (int k=0; k < 4-ss.length(); k++) {
            out.append('0');
          }
          out.append(ss.toUpperCase());
        }
        else{
          out.append(ch);
        }
      }
    }//for
  }
  
  
  private void appendValue(Object value) throws IOException {
    if (value == null) {
      out.append("null");
      
    } else if (value instanceof String) {
      out.append('"');
      appendString(value.toString());
      out.append('"');
      
    } else if (value instanceof Double) {
      var num = (Double) value;
      if (num.isInfinite() || num.isNaN())
        out.append("null");
      else
        out.append(value.toString());
      
    } else if (value instanceof Float) {
      var num = (Float) value;
      if (num.isInfinite() || num.isNaN())
        out.append("null");
      else
        out.append(value.toString());
      
    } else if (value instanceof Map) {
      printImpl((Map<?,?>) value);
      
    } else if (value instanceof List) {
      printImpl((List<?>) value);
      
//    } else if (value instanceof Number || value instanceof Boolean) {
//      out.append(value.toString());
      
    } else {
      out.append(value.toString());
      
    }
  }

}

It works for JSONObject and JSONArray even tho it has no dependeny on them.. cuz these are regular Map and List objects resp. (and the fact code was lifted from same lib).

https://github.com/crums-io/io-util/blob/master/src/main/java/io/crums/util/json/JsonPrinter.java

数理化全能战士 2024-10-07 17:59:11

这将是打印对象的漂亮版本的公共方法(您需要安装 Gson 依赖项:

import com.google.gson.GsonBuilder;
...

public void printMe(){
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String prettyJSON = gson.toJson(this);
    System.out.println(printable);
}

This would be a public method to print a pretty version of your object (You need the Gson dependency installed:

import com.google.gson.GsonBuilder;
...

public void printMe(){
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String prettyJSON = gson.toJson(this);
    System.out.println(printable);
}
慵挽 2024-10-07 17:59:11

您可以使用小型 json

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

You can use small json library

String jsonstring = ....;
JsonValue json = JsonParser.parse(jsonstring);
String jsonIndendedByTwoSpaces = json.toPrettyString("  ");
被翻牌 2024-10-07 17:59:11

我还使用 org.json.simple 包。我只是对格式化程序进行了编码,但由于我编写的程序中的 JSON 对象中没有空值、数字或布尔值,所以我只对字符串、对象和数组进行了编码。如果有人感兴趣,请让其成为公共领域。欢迎您添加缺少的数据类型(注释中说“它是一个字符串”)。另外,您可以添加缩进作为参数,而我的只有两个空格。请在测试改进后重新分享。

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

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.

Usage: printJsonObject(jsonObject, "");

Functions:

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

栖迟 2024-10-07 17:59:11

Underscore-java 有静态方法 U.formatJson(json)
支持五种格式类型:2、3、4、制表符和紧凑。 实例

import com.github.underscore.U;

import static com.github.underscore.Json.JsonStringBuilder.Step.TABS;
import static com.github.underscore.Json.JsonStringBuilder.Step.TWO_SPACES;

public class MyClass {

    public static void main(String args[]) {
        String json = "{\"Price\": {"
        + "    \"LineItems\": {"
        + "        \"LineItem\": {"
        + "            \"UnitOfMeasure\": \"EACH\", \"Quantity\": 2, \"ItemID\": \"ItemID\""
        + "        }"
        + "    },"
        + "    \"Currency\": \"USD\","
        + "    \"EnterpriseCode\": \"EnterpriseCode\""
        + "}}";
        System.out.println(U.formatJson(json, TWO_SPACES)); 
        System.out.println(U.formatJson(json, TABS)); 
    }
}

输出:

{
  "Price": {
    "LineItems": {
      "LineItem": {
        "UnitOfMeasure": "EACH",
        "Quantity": 2,
        "ItemID": "ItemID"
      }
    },
    "Currency": "USD",
    "EnterpriseCode": "EnterpriseCode"
  }
}
{
    "Price": {
        "LineItems": {
            "LineItem": {
                "UnitOfMeasure": "EACH",
                "Quantity": 2,
                "ItemID": "ItemID"
            }
        },
        "Currency": "USD",
        "EnterpriseCode": "EnterpriseCode"
    }
}

Underscore-java has static method U.formatJson(json).
Five format types are supported: 2, 3, 4, tabs and compact. Live example

import com.github.underscore.U;

import static com.github.underscore.Json.JsonStringBuilder.Step.TABS;
import static com.github.underscore.Json.JsonStringBuilder.Step.TWO_SPACES;

public class MyClass {

    public static void main(String args[]) {
        String json = "{\"Price\": {"
        + "    \"LineItems\": {"
        + "        \"LineItem\": {"
        + "            \"UnitOfMeasure\": \"EACH\", \"Quantity\": 2, \"ItemID\": \"ItemID\""
        + "        }"
        + "    },"
        + "    \"Currency\": \"USD\","
        + "    \"EnterpriseCode\": \"EnterpriseCode\""
        + "}}";
        System.out.println(U.formatJson(json, TWO_SPACES)); 
        System.out.println(U.formatJson(json, TABS)); 
    }
}

Output:

{
  "Price": {
    "LineItems": {
      "LineItem": {
        "UnitOfMeasure": "EACH",
        "Quantity": 2,
        "ItemID": "ItemID"
      }
    },
    "Currency": "USD",
    "EnterpriseCode": "EnterpriseCode"
  }
}
{
    "Price": {
        "LineItems": {
            "LineItem": {
                "UnitOfMeasure": "EACH",
                "Quantity": 2,
                "ItemID": "ItemID"
            }
        },
        "Currency": "USD",
        "EnterpriseCode": "EnterpriseCode"
    }
}
萌吟 2024-10-07 17:59:10

Google 的 GSON 可以以一种很好的方式做到这一点:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJsonString);
String prettyJsonString = gson.toJson(je);

或者因为现在建议使用静态解析方法JsonParser 你也可以使用它:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement je = JsonParser.parseString​(uglyJsonString);
String prettyJsonString = gson.toJson(je);

这是导入语句:

import com.google.gson.*;

这是 Gradle 依赖项:

implementation 'com.google.code.gson:gson:2.8.7'

Google's GSON can do this in a nice way:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJsonString);
String prettyJsonString = gson.toJson(je);

or since it is now recommended to use the static parse method from JsonParser you can also use this instead:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement je = JsonParser.parseString​(uglyJsonString);
String prettyJsonString = gson.toJson(je);

Here is the import statement:

import com.google.gson.*;

Here is the Gradle dependency:

implementation 'com.google.code.gson:gson:2.8.7'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文