[英]Pretty-Print JSON in Java
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'
我使用org.json內置方法來漂亮地打印數據。
JSONObject json = new JSONObject(jsonString); // Convert text to object
System.out.println(json.toString(4)); // Print it with specified indentation
JSON 中字段的順序根據定義是隨機的。 具體順序取決於解析器實現。
與傑克遜( com.fasterxml.jackson.databind
):
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject))
來自: 如何啟用漂亮的打印 JSON 輸出 (Jackson)
我知道這已經在答案中了,但我想在這里單獨編寫它,因為很有可能,您已經將 Jackson 作為依賴項,因此您只需要一行額外的代碼
好像GSON支持這個,雖然我不知道你是否想從你正在使用的庫中切換。
從用戶指南:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);
如果您使用 Java API 進行 JSON 處理 (JSR-353) 實現,那么您可以在創建JsonGeneratorFactory
時指定JsonGenerator.PRETTY_PRINTING
屬性。
以下示例最初發布在我的博客文章中。
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();
我的情況是我的項目使用不支持漂亮打印的遺留(非 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");
使用 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 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);
(或者)
Buffer buffer = new Buffer();
JsonWriter jsonWriter = JsonWriter.of(buffer);
jsonWriter.setIndent(" ");
jsonAdapter.toJson(jsonWriter, emp1);
json = buffer.readUtf8();
大多數現有答案要么依賴於某些外部庫,要么需要特殊的 Java 版本。 這是一個簡單的代碼來漂亮地打印一個 JSON 字符串,只使用通用的 Java API(在 Java 7 中可用,但沒有嘗試過舊版本)。
基本思想是根據 JSON 中的特殊字符來觸發格式。 例如,如果觀察到 '{' 或 '[',代碼將創建一個新行並增加縮進級別。
免責聲明:我只針對一些簡單的 JSON 情況(基本鍵值對、列表、嵌套 JSON)測試了這個,所以它可能需要一些工作來處理更一般的 JSON 文本,比如帶引號的字符串值,或特殊字符(\\n、\\等)。
/**
* 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>
在一行中:
String niceFormattedJson = JsonWriter.formatJson(jsonString)
json-io 庫 ( https://github.com/jdereg/json-io ) 是一個小型 (75K) 庫,除了 JDK 之外沒有其他依賴項。
除了漂亮的打印 JSON 之外,您還可以將 Java 對象(帶有循環的整個 Java 對象圖)序列化為 JSON,並將它們讀入。
遵循 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);
或者,您可以像下面一樣使用 Jackson
ObjectMapper mapper = new ObjectMapper();
String perttyStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
希望這有幫助!
new JsonParser().parse(...)
是@deprecated
基於Gson 2.8.6的 javadoc :
不需要實例化這個類,而是使用靜態方法。
JsonParser靜態方法:
JsonParser.parseString(jsonString);
JsonParser.parseReader(reader);
套餐:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;
例子:
private Gson GSON = new GsonBuilder().setPrettyPrinting().create();
public static String getPerfectJSON(String unformattedJSON) {
String perfectJSON = GSON.toJson(JsonParser.parseString(unformattedJSON));
return perfectJSON;
}
使用 Maven 的Google Gson依賴項:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
這對我有用,使用傑克遜:
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(JSONString)
您可以使用小型json庫
String jsonstring = ....;
JsonValue json = JsonParser.parse(jsonstring);
String jsonIndendedByTwoSpaces = json.toPrettyString(" ");
我也使用 org.json.simple 包。 我只是對格式化程序進行了編碼,但是由於我編寫的程序中的 JSON 對象中沒有空值、數字或布爾值,因此我只對字符串、對象和數組進行了編碼。 如果有人感興趣,讓這只是在公共領域。 歡迎您添加缺少的數據類型(它在注釋中說“它是一個字符串”)。 此外,您可以添加縮進作為參數,而我的只有兩個空格。 請在測試您的改進后重新分享。
用法: 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 + "]");
}
所以我也喜歡json-simple
庫,並研究了漂亮的打印輸出。 不幸的是,雖然這是一個懸而未決的問題,但我找不到任何代碼。 所以我想我會嘗試一下,這就是我想出的(使用他們自己的來源)。
public class JsonPrinter {
public static String toJson(Map<?,?> map) {
StringBuilder out = new StringBuilder(32);
new JsonPrinter(out).print(map);
return out.toString();
}
public static String toJson(List<?> list) {
StringBuilder out = new StringBuilder(32);
new JsonPrinter(out).print(list);
return out.toString();
}
private final Appendable out;
private final String indentUnit;
private final String newLine;
private int indents;
public JsonPrinter(Appendable out) {
this(out, " ", System.lineSeparator());
}
/**
*
*/
public JsonPrinter(Appendable out, String indentUnit, String newLine) {
this.out = Objects.requireNonNull(out, "null out");
this.indentUnit = Objects.requireNonNull(indentUnit, "null indentUnit");
this.newLine = Objects.requireNonNull(newLine, "null newLine");
if (!indentUnit.isBlank())
throw new IllegalArgumentException(
"indentUnit must be a blank sequence (quoted): '" + indentUnit + "'");
if (!"\r\n".equals(newLine) && ! "\n".equals(newLine))
throw new IllegalArgumentException(
"unrecognized newLine (quoted): '" + newLine + "'");
}
public void print(List<?> list) throws UncheckedIOException {
try {
assert indents == 0;
printImpl(list);
assert indents == 0;
} catch (IOException iox) {
throw new UncheckedIOException("on print(List): " + list, iox);
}
}
public void print(Map<?,?> map) throws UncheckedIOException {
try {
assert indents == 0;
printImpl(map);
assert indents == 0;
} catch (IOException iox) {
throw new UncheckedIOException("on print(Map): " + map, iox);
}
}
protected void printImpl(List<?> list) throws IOException {
if (list == null) {
out.append("null");
return;
}
boolean first = true;
var iter = list.iterator();
open('[');
while (iter.hasNext()) {
if (first)
first = false;
else
out.append(',');
out.append(newLine);
appendIndents();
appendValue(iter.next());
}
close(']');
}
protected void printImpl(Map<?, ?> map) throws IOException {
if (map == null) {
out.append("null");
return;
}
boolean first = true;
var iter = map.entrySet().iterator();
open('{');
while (iter.hasNext()) {
if (first)
first = false;
else
out.append(',');
out.append(newLine);
appendIndents();
var entry = iter.next();
print(entry.getKey().toString(), entry.getValue());
}
close('}');
}
private void open(char c) throws IOException {
out.append(c);
++indents;
}
private void close(char c) throws IOException {
--indents;
out.append(newLine);
appendIndents();
out.append(c);
}
private void appendIndents() throws IOException {
for (int count = indents; count-- > 0; )
out.append(indentUnit);
}
private void print(String key, Object value) throws IOException {
out.append('"');
appendString(key);
out.append('"').append(':').append(' ');
appendValue(value);
}
private void appendString(String s) throws IOException {
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch(ch){
case '"':
out.append("\\\"");
break;
case '\\':
out.append("\\\\");
break;
case '\b':
out.append("\\b");
break;
case '\f':
out.append("\\f");
break;
case '\n':
out.append("\\n");
break;
case '\r':
out.append("\\r");
break;
case '\t':
out.append("\\t");
break;
case '/':
out.append("\\/");
break;
default:
//Reference: http://www.unicode.org/versions/Unicode5.1.0/
if ((ch>='\u0000' && ch<='\u001F') || (ch>='\u007F' && ch<='\u009F') || (ch>='\u2000' && ch<='\u20FF')) {
String ss = Integer.toHexString(ch);
out.append("\\u");
for (int k=0; k < 4-ss.length(); k++) {
out.append('0');
}
out.append(ss.toUpperCase());
}
else{
out.append(ch);
}
}
}//for
}
private void appendValue(Object value) throws IOException {
if (value == null) {
out.append("null");
} else if (value instanceof String) {
out.append('"');
appendString(value.toString());
out.append('"');
} else if (value instanceof Double) {
var num = (Double) value;
if (num.isInfinite() || num.isNaN())
out.append("null");
else
out.append(value.toString());
} else if (value instanceof Float) {
var num = (Float) value;
if (num.isInfinite() || num.isNaN())
out.append("null");
else
out.append(value.toString());
} else if (value instanceof Map) {
printImpl((Map<?,?>) value);
} else if (value instanceof List) {
printImpl((List<?>) value);
// } else if (value instanceof Number || value instanceof Boolean) {
// out.append(value.toString());
} else {
out.append(value.toString());
}
}
}
它適用於JSONObject
和JSONArray
即使它對它們沒有任何依賴。因為這些是常規的Map
和List
對象。 (並且事實代碼是從同一個 lib 中提取的)。
https://github.com/crums-io/io-util/blob/master/src/main/java/io/crums/util/json/JsonPrinter.java
這將是一種打印漂亮版本的 object 的公共方法(您需要安裝 Gson 依賴項:
import com.google.gson.GsonBuilder;
...
public void printMe(){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String prettyJSON = gson.toJson(this);
System.out.println(printable);
}
U.formatJson(json)
-java有靜態方法U.formatJson(json)
。 支持五種格式類型:2、3、4、制表符和緊湊。 活生生的例子
import com.github.underscore.lodash.U;
import static com.github.underscore.lodash.Json.JsonStringBuilder.Step.TABS;
import static com.github.underscore.lodash.Json.JsonStringBuilder.Step.TWO_SPACES;
public class MyClass {
public static void main(String args[]) {
String json = "{\"Price\": {"
+ " \"LineItems\": {"
+ " \"LineItem\": {"
+ " \"UnitOfMeasure\": \"EACH\", \"Quantity\": 2, \"ItemID\": \"ItemID\""
+ " }"
+ " },"
+ " \"Currency\": \"USD\","
+ " \"EnterpriseCode\": \"EnterpriseCode\""
+ "}}";
System.out.println(U.formatJson(json, TWO_SPACES));
System.out.println(U.formatJson(json, TABS));
}
}
輸出:
{
"Price": {
"LineItems": {
"LineItem": {
"UnitOfMeasure": "EACH",
"Quantity": 2,
"ItemID": "ItemID"
}
},
"Currency": "USD",
"EnterpriseCode": "EnterpriseCode"
}
}
{
"Price": {
"LineItems": {
"LineItem": {
"UnitOfMeasure": "EACH",
"Quantity": 2,
"ItemID": "ItemID"
}
},
"Currency": "USD",
"EnterpriseCode": "EnterpriseCode"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.