
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
javax.json包提供了一个对象模型API来处理JSON。对象模型API是一个高级API,为JSON对象和数组结构提供了不可变的对象模型。这些JSON结构可以使用JsonObject和JsonArray接口表示为对象模型。我们可以使用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"
}以上就是如何使用Java中的javax.json API对JSON进行漂亮的打印?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号