gpt4 book ai didi

java - JSON 格式说明换行符

转载 作者:行者123 更新时间:2023-12-01 12:35:30 24 4
gpt4 key购买 nike

我有一个关于 json 格式的问题。我需要为名为 DataTables 的 jquery 插件生成以下 json...

 {
"aaData": [{
"name": "Zane Music",
"address": "162 Castle Hill",
"town": "Berkshire"
}, {
"name": "Zander Exports",
"address": "34 Sapcote Trading Centre",
"town": "London"
}]
}

为了尝试实现这一目标,我使用 org.json.simple 并成功生成了以下内容...

 {
"aaData": [{
"name": "Zane Music",
"address": "162 Castle Hill",
"town": "Berkshire"
}, {
"name": "Zander Exports",
"address": "34 Sapcote Trading Centre",
"town": "London"
}]
}

即它们是相同的,但第二个列表缺少换行符并且格式不正确。

我的问题是这对消费者来说重要吗?将 json 格式化为良好的做法是否是一个好习惯?还有没有办法让它格式化得很好?

使用 json simple,您可以通过在域对象中添加一个方法来指定 json,如下所示...

public String toJSONString() {
JSONObject obj = new JSONObject();
obj.put("location", _location);
obj.put("locationName", _locationName);
obj.put("region", _region);
return obj.toString();
}

所以我想我可以在必要时添加换行符。

这是正确的方法吗/有必要吗?

谢谢

最佳答案

My question is does this matter for the consumer and is it goodpractice to have the json nicely formatted?

JSON specification

Insignificant whitespace is allowed before or after any of the six structural characters.

所以,不,空格没有意义。正确的 JSON 使用者不会看到差异。格式化仅适合人眼。

Also is there a way to make it nicely formatted?

我不知道 org.json,但一些 JSON 解析库有一个实用程序或配置选项。考虑使用 Gson 或 Jackson 以及 pretty-print 选项。 Here are some more options.

关于java - JSON 格式说明换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25637185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com