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

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

问题描述

我有一个有效的JSON字符串,我想要整理/格式化,使得每个属性/值对都在自己的行上,等等(当前是在一行中,没有空格/换行符)。



我使用Apache Sling JSONObject 来建模我的JSON对象,并把它变成一个String,所以如果Sling JSONObject 可以被设置为输出一个整洁的字符串(我认为它不可能)。



<如果我需要一个第三方lib,我更喜欢一个w尽可能少的依赖关系(比如只需要std JDK库的Jackson)。 解决方案



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

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



创建此JSONObject的JSON文本。 g:这个方法假设
的数据结构是非循环的。



参数:

indentFactor - 要添加到每个级别
的缩进的空格数。返回:对象的可打印,可显示,可移植,
可传递的表示形式,以{(left
brace)开头,结尾为}(右大括号)。



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



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 w no spaces/line breaks).

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.

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

解决方案

You don't need an outside library.

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) throws JSONException

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

Parameters:

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).

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

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

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