我有一個緊湊的JSON字符串,我想在Java中很好地格式化它,而不必首先反序列化它 - 例如,就像jsonlint.org一樣。有沒有圖書館提供這些?如何用Java打印現有的JSON數據?
類似的XML解決方案也不錯。
我有一個緊湊的JSON字符串,我想在Java中很好地格式化它,而不必首先反序列化它 - 例如,就像jsonlint.org一樣。有沒有圖書館提供這些?如何用Java打印現有的JSON數據?
類似的XML解決方案也不錯。
如果您正在使用傑克遜,你可以很容易地在您的ObjectMapper
配置SerializationFeature
實現這一目標:
com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.writeValueAsString(<yourObject>);
完蛋了。
在一個行:
String niceFormattedJson = JsonWriter.formatJson(jsonString)
或
System.out.println(JsonWriter.formatJson(jsonString.toString()));
的JSON-IO libray(https://github.com/jdereg/json-io)是小的(75K)庫,沒有其他依賴比JDK。
除了漂亮的印刷JSON,你可以序列化的Java對象(整個Java對象圖與週期)到JSON,以及在閱讀它們。
使用這個小庫,對輸出格式進行了一些修改。謝謝你讓我知道。 – 2014-10-28 10:40:31
這不僅是第一個在我的環境中工作的解決方案,它最終證實我知道如何使用Gradle來正確拉入第三方庫!美好的一天,謝謝! – Shadoninja 2015-12-26 21:00:33
int spacesToIndentEachLevel = 2;
new JSONObject(jsonString).toString(spacesToIndentEachLevel);
使用org.json.JSONObject
(內置於JavaEE的和安卓)
這是什麼庫使用?因爲它不是一個非常有用的答案。 – 2014-10-28 09:47:41
@Andrew Backer,這不是圖書館。正如Heath Borders所說的那樣,它被嵌入到Android庫中。我已經測試過了,沒有任何圖書館,它完美的工作。 – tambykojak 2014-11-25 08:11:25
嗯......我沒有爲Android開發,也沒有部署到Java EE容器......因此需要澄清。感謝您補充:)因此,對於像我這樣的人,發佈一個針對SE的Java應用程序,它會是一個庫,比如'org.json:json:20090211'? – 2014-11-26 09:29:44
我發現那位一個非常簡單的解決方案:
<dependency>
<groupId>com.cedarsoftware</groupId>
<artifactId>json-io</artifactId>
<version>4.5.0</version>
</dependency>
Java代碼:
import com.cedarsoftware.util.io.JsonWriter;
//...
String jsonString = "json_string_plain_text";
System.out.println(JsonWriter.formatJson(jsonString));
使用gson。 https://www.mkyong.com/java/how-to-enable-pretty-print-json-output-gson/
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(my_bean);
輸出
{
"name": "mkyong",
"age": 35,
"position": "Founder",
"salary": 10000,
"skills": [
"java",
"python",
"shell"
]
}
另一種使用GSON:
String json_String_to_print = ...
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
return gson.toJson(jp.parse(json_String_to_print));
它可以用來當你沒有豆爲susemi99的職位。
通過漂亮的打印,你的意思是顏色代碼,縮進還是兩者? – Eric 2011-05-31 09:14:17
JSONObject有一個'toString(int)',你可以爲漂亮的打印提供間距。 – 2011-05-31 09:14:19
@Eric:只需縮進。 – neu242 2011-05-31 10:26:11