在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"
}热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短