JSON String tidy/formatter for Java(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字符串整洁/格式化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java的JSON字符串整洁/格式化程序
基础教程推荐
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
