使用 Java 中的 javax.json API 漂亮地列印 JSON?\n
javax.json 包提供了用於處理 JSON 的物件模型 API。物件模型 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"
}
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP