Java的JSON字符串整洁/格式化程序

2023-03-02Java开发问题
79

本文介绍了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字符串整洁/格式化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13