在Java中使用javax.json API漂亮地打印JSON?

javax.json 包提供了 对象模型API处理JSON。对象模型API是一种高级API,可为JSON对象和数组结构提供不可变的对象模型。可以使用JsonObject JsonArray 接口将这些JSON结构表示为对象模型。我们可以使用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"
}