我使用JSON -simple,我需要漂亮地打印JSON数据(使其更易于阅读)。
我还没能在那个库中找到这个功能。 这通常是如何实现的?
我使用JSON -simple,我需要漂亮地打印JSON数据(使其更易于阅读)。
我还没能在那个库中找到这个功能。 这通常是如何实现的?
当前回答
I also use the org.json.simple package. I have simply coded the formatter, but since I don't have nulls, numbers or booleans in my JSON objects in the program that I wrote, I only coded for strings, objects and arrays. If anyone is interested, let this just be in the public domain. You are welcome to add the missing data types (where it says in the comment "it's a string"). Also, you can add the indentation as a parameter whereas mine is just two spaces. Please reshare after you've tested your improvements.
用法: printJsonObject(jsonObject, “”);
功能:
public static void printJsonObject(JSONObject object, String prefix) {
boolean notFirst = false;
System.out.println(prefix + "{");
for (Object key : object.keySet()) {
if (notFirst) {
System.out.println(", ");
}
notFirst = true;
Object value = object.get(key);
System.out.print(prefix + " " + "\"" + key + "\"" + ": ");
if (value instanceof JSONObject) {
printJsonObject((JSONObject) value, prefix + " ");
} else if (value instanceof JSONArray) {
printJsonArray((JSONArray) value, prefix + " ");
} else { // it's a string
System.out.print("\"" + value + "\"");
}
}
System.out.println("");
System.out.print(prefix + "}");
}
public static void printJsonArray(JSONArray array, String prefix) {
boolean notFirst = false;
System.out.println("[");
for (Object item : array) {
if (notFirst) {
System.out.println(", ");
}
notFirst = true;
if (item instanceof JSONObject) {
printJsonObject((JSONObject) item, prefix + " ");
} else if (item instanceof JSONArray) {
printJsonArray((JSONArray) item, prefix + " ");
} else {
System.out.print(prefix + " " + "\"" + item + "\"");
}
}
System.out.println("");
System.out.print(prefix + "]");
}
其他回答
使用org json。参考链接
JSONObject jsonObject = new JSONObject(obj);
String prettyJson = jsonObject.toString(4);
使用Gson。参考链接
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(obj);
使用杰克逊。参考链接
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(obj);
使用Genson的律师。参考链接。
Genson prettyGenson = new GensonBuilder().useIndentation(true).create();
String prettyJson = prettyGenson.serialize(obj);
使用javax.json。参考链接。
Map<String, Boolean> config = new HashMap<>();
config.put(JsonGenerator.PRETTY_PRINTING, true);
JsonWriterFactory writerFactory = Json.createWriterFactory(config);
Writer writer = new StringWriter();
writerFactory.createWriter(writer).write(jsonObject);
String json = writer.toString();
使用Moshi库。参考链接。
String json = jsonAdapter.indent(" ").toJson(emp1);
(OR)
Buffer buffer = new Buffer();
JsonWriter jsonWriter = JsonWriter.of(buffer);
jsonWriter.setIndent(" ");
jsonAdapter.toJson(jsonWriter, emp1);
json = buffer.readUtf8();
我的情况是我的项目使用了不支持漂亮打印的遗留(非jsr) JSON解析器。然而,我需要生成漂亮的JSON样本;这是可能的,而不需要添加任何额外的库,只要你使用Java 7及以上:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine scriptEngine = manager.getEngineByName("JavaScript");
scriptEngine.put("jsonString", jsonStringNoWhitespace);
scriptEngine.eval("result = JSON.stringify(JSON.parse(jsonString), null, 2)");
String prettyPrintedJson = (String) scriptEngine.get("result");
漂亮的打印与GSON一行:
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().parse(jsonString)));
除了内联之外,这等价于已接受的答案。
遵循JSON-P 1.0规范(JSR-353),对于给定的JsonStructure (JsonObject或JsonArray),一个更当前的解决方案可能是这样的:
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.json.Json;
import javax.json.JsonStructure;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;
public class PrettyJson {
private static JsonWriterFactory FACTORY_INSTANCE;
public static String toString(final JsonStructure status) {
final StringWriter stringWriter = new StringWriter();
final JsonWriter jsonWriter = getPrettyJsonWriterFactory()
.createWriter(stringWriter);
jsonWriter.write(status);
jsonWriter.close();
return stringWriter.toString();
}
private static JsonWriterFactory getPrettyJsonWriterFactory() {
if (null == FACTORY_INSTANCE) {
final Map<String, Object> properties = new HashMap<>(1);
properties.put(JsonGenerator.PRETTY_PRINTING, true);
FACTORY_INSTANCE = Json.createWriterFactory(properties);
}
return FACTORY_INSTANCE;
}
}
你可以像下面这样使用Gson
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonString = gson.toJson(object);
从post JSON漂亮打印使用Gson
或者,你可以像下面这样使用Jackson
ObjectMapper mapper = new ObjectMapper();
String perttyStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
漂亮的Java JSON打印(Jackson)
希望这对你有所帮助!