我正在使用json-simple,需要将JSON数据美化(使其更易读)。
在该库中未能找到此功能。 通常如何实现此功能?
我正在使用json-simple,需要将JSON数据美化(使其更易读)。
在该库中未能找到此功能。 通常如何实现此功能?
Google的GSON可以以优雅的方式实现此功能:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJsonString);
String prettyJsonString = gson.toJson(je);
或者,由于现在建议使用JsonParser的静态解析方法,因此您也可以使用它代替:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement je = JsonParser.parseString(uglyJsonString);
String prettyJsonString = gson.toJson(je);
这是导入语句:
import com.google.gson.*;
以下是Gradle依赖项:
implementation 'com.google.code.gson:gson:2.8.7'
scriptEngine.eval("result = JSON.stringify(JSON.parse(jsonString), null, 2)");
- AgnesGsonBuilder
,由于我使用的是gson.toJson(object)
,所以我只需要将实例化从Gson gson = new Gson();
更改为Gson gson = new GsonBuilder().setPrettyPrinting().create();
,我的代码继续工作,但漂亮地打印了对象而不是单行。 - cptully我使用了 org.json 的内置方法对数据进行漂亮格式化。
import org.json.JSONObject;
JSONObject json = new JSONObject(jsonString); // Convert text to object
System.out.println(json.toString(4)); // Print it with specified indentation
JSON中字段的顺序是按定义随机排列的。特定顺序取决于解析器的实现。
使用Jackson (com.fasterxml.jackson.databind
):
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject))
我知道这已经在答案中了,但我想在这里单独写一下,因为很有可能你已经有了Jackson依赖,所以你只需要加一行额外的代码。
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(mapper.readTree(jsonString));```
- Josejulio看起来GSON支持这个功能,不过我不知道你是否想要从你现在使用的库更改。
来自用户指南:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);
使用org json。参考链接
JSONObject jsonObject = new JSONObject(obj);
String prettyJson = jsonObject.toString(4);
使用Gson。参考链接
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(obj);
使用Jackson。参考链接
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(obj);
Genson prettyGenson = new GensonBuilder().useIndentation(true).create();
String prettyJson = prettyGenson.serialize(obj);
使用javax.json。参考link。
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 库。参考 link。
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();
import java.util.*;
import javax.json.Json;
import javax.json.stream.*;
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JsonGenerator.PRETTY_PRINTING, true);
JsonGeneratorFactory jgf = Json.createGeneratorFactory(properties);
JsonGenerator jg = jgf.createGenerator(System.out);
jg.writeStartObject() // {
.write("name", "Jane Doe") // "name":"Jane Doe",
.writeStartObject("address") // "address":{
.write("type", 1) // "type":1,
.write("street", "1 A Street") // "street":"1 A Street",
.writeNull("city") // "city":null,
.write("verified", false) // "verified":false
.writeEnd() // },
.writeStartArray("phone-numbers") // "phone-numbers":[
.writeStartObject() // {
.write("number", "555-1111") // "number":"555-1111",
.write("extension", "123") // "extension":"123"
.writeEnd() // },
.writeStartObject() // {
.write("number", "555-2222") // "number":"555-2222",
.writeNull("extension") // "extension":null
.writeEnd() // }
.writeEnd() // ]
.writeEnd() // }
.close();
我的情况是,我的项目使用了一个不支持漂亮打印的旧版(non-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");
/**
* A simple implementation to pretty-print JSON file.
*
* @param unformattedJsonString
* @return
*/
public static String prettyPrintJSON(String unformattedJsonString) {
StringBuilder prettyJSONBuilder = new StringBuilder();
int indentLevel = 0;
boolean inQuote = false;
for(char charFromUnformattedJson : unformattedJsonString.toCharArray()) {
switch(charFromUnformattedJson) {
case '"':
// switch the quoting status
inQuote = !inQuote;
prettyJSONBuilder.append(charFromUnformattedJson);
break;
case ' ':
// For space: ignore the space if it is not being quoted.
if(inQuote) {
prettyJSONBuilder.append(charFromUnformattedJson);
}
break;
case '{':
case '[':
// Starting a new block: increase the indent level
prettyJSONBuilder.append(charFromUnformattedJson);
indentLevel++;
appendIndentedNewLine(indentLevel, prettyJSONBuilder);
break;
case '}':
case ']':
// Ending a new block; decrese the indent level
indentLevel--;
appendIndentedNewLine(indentLevel, prettyJSONBuilder);
prettyJSONBuilder.append(charFromUnformattedJson);
break;
case ',':
// Ending a json item; create a new line after
prettyJSONBuilder.append(charFromUnformattedJson);
if(!inQuote) {
appendIndentedNewLine(indentLevel, prettyJSONBuilder);
}
break;
default:
prettyJSONBuilder.append(charFromUnformattedJson);
}
}
return prettyJSONBuilder.toString();
}
/**
* Print a new line with indention at the beginning of the new line.
* @param indentLevel
* @param stringBuilder
*/
private static void appendIndentedNewLine(int indentLevel, StringBuilder stringBuilder) {
stringBuilder.append("\n");
for(int i = 0; i < indentLevel; i++) {
// Assuming indention using 2 spaces
stringBuilder.append(" ");
}
}
现在可以使用JSONLib库来实现这一点:
http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html
如果(仅当)您使用重载的toString(int indentationFactor)
方法而不是标准的toString()
方法。
我已经在以下API版本上验证了这一点:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>