Java的JSON字符串整洁/格式化程序 [英] JSON String tidy/formatter for Java

查看:33
本文介绍了Java的JSON字符串整洁/格式化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有效的 JSON 字符串,我想对其进行整理/格式化,以便每个属性/值对都在自己的行上,等等(它目前在一行上,没有空格/换行符).

I have a valid JSON String that I want to tidy/format such that each property/value pair is on its own line, etc. (it currently is on one line with no spaces/line breaks).

我正在使用 Apache Sling JSONObject 对我的 JSON 对象进行建模并将其转换为字符串,因此如果可以将 Sling JSONObject 设置为输出整洁的字符串(我不认为它可以)那也可以.

I am using the Apache Sling JSONObject to model my JSON Object and turn it into a String, so if the Sling JSONObject can be set to output a tidy string (which I do not think it can) that would work too.

如果我需要一个 3rd 方库,我会更喜欢依赖项尽可能少的库(例如 Jackson,它只需要 std JDK 库).

If I need a 3rd party lib I would prefer one with as few dependencies as possibles (such as Jackson which only requires the std JDK libs).

推荐答案

你不需要外部库.

在 Sling 的 JSONObject 中使用内置的漂亮打印机:http://sling.apache.org/apidocs/sling5/org/apache/sling/commons/json/JSONObject.html#toString(int)

Use the built in pretty printer in Sling's JSONObject: http://sling.apache.org/apidocs/sling5/org/apache/sling/commons/json/JSONObject.html#toString(int)

public java.lang.String toString(int indentFactor)抛出 JSONException

public java.lang.String toString(int indentFactor) throws JSONException

制作此 JSONObject 的漂亮打印 JSON 文本.警告:此方法假定数据结构是非循环的.

Make a prettyprinted JSON text of this JSONObject. Warning: This method assumes that the data structure is acyclical.

参数:

indentFactor - 添加到每个级别的空格数的缩进.

indentFactor - The number of spaces to add to each level of indentation.

返回:可打印、可显示、可移植、对象的可传输表示,以 { 开头(左大括号)并以 } 结尾(右大括号).

Returns: a printable, displayable, portable, transmittable representation of the object, beginning with { (left brace) and ending with } (right brace).

抛出:JSONException - 如果对象包含无效数字.

Throws: JSONException - If the object contains an invalid number.

这篇关于Java的JSON字符串整洁/格式化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆