我们可以在下面的示例中实现漂亮的打印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 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进行漂亮的打印?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!