Java 中的漂亮打印 JSON [英] Pretty-Print JSON in Java
本文介绍了Java 中的漂亮打印 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 json-simple 并且我需要漂亮地打印 JSON 数据(使其更具可读性).
I'm using json-simple and I need to pretty-print JSON data (make it more human readable).
我一直无法在该库中找到此功能.这通常是如何实现的?
I haven't been able to find this functionality within that library. How is this commonly achieved?
推荐答案
Google 的 GSON 可以在一个不错的方法:
Google's GSON can do this in a nice way:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJsonString);
String prettyJsonString = gson.toJson(je);
或者因为现在建议使用来自 JsonParser 的静态解析方法,您也可以使用它来代替:
or since it is now recommended to use the static parse method from JsonParser you can also use this instead:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement je = JsonParser.parseString(uglyJsonString);
String prettyJsonString = gson.toJson(je);
这是导入语句:
import com.google.gson.*;
这是 Gradle 依赖项:
Here is the Gradle dependency:
implementation 'com.google.code.gson:gson:2.8.7'
这篇关于Java 中的漂亮打印 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文