首页 > 文章列表 > 如何使用Java中的javax.json API对JSON进行漂亮的打印?

如何使用Java中的javax.json API对JSON进行漂亮的打印?

176 2023-08-24

javax.json包提供了一个对象模型API来处理JSON。对象模型API是一个高级API,为JSON对象和数组结构提供了不可变的对象模型。这些JSON结构可以使用JsonObjectJsonArray接口表示为对象模型。我们可以使用JsonGenerator接口以流式方式将JSON数据写入输出。 JsonGenerator.PRETTY_PRINTING是一个配置属性,用于生成漂亮的JSON。

我们可以在下面的示例中实现漂亮的打印JSON。

示例

import java.io.*;
import java.util.*;
import javax.json.*;
import javax.json.stream.*;
public class JSONPrettyPrintTest {
   public static void main(String args[]) {
      String jsonString = "{"name":"Raja Ramesh","age":"35","salary":"40000"}";
      StringWriter sw = new StringWriter();
      try {
         JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
         JsonObject jsonObj = jsonReader.readObject();
         Map<String, Object> map = new HashMap<>();
         map.put(JsonGenerator.PRETTY_PRINTING, true);
         JsonWriterFactory writerFactory = Json.createWriterFactory(map);
         JsonWriter jsonWriter = writerFactory.createWriter(sw);
         jsonWriter.writeObject(jsonObj);
         jsonWriter.close();
      } catch(Exception e) {
         e.printStackTrace();
      }
      String prettyPrint = sw.toString();
      System.out.println(prettyPrint); // pretty print JSON
   }
}

输出

{
   "name": "Raja Ramesh",
 "age": "35",
  "salary": "40000"
}