使用 org.json 在 Java 中创建 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16271766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:29:01  来源:igfitidea点击:

Creating JSON in java using org.json

javajsonorg.json

提问by raju

I am trying to create a json string in java using org.json library and following is the code snippet.

我正在尝试使用 org.json 库在 java 中创建一个 json 字符串,以下是代码片段。

JSONArray jSONArray = new JSONArray();
JSONObject jSONObject = new JSONObject();
jSONObject.accumulate("test", jSONArray);
System.out.println(jSONObject.toString());

I expected it to print

我希望它打印

{"test":[]} 

while it prints

打印时

{"test":[[]]}

回答by thepoosh

instead of using accumulateuse putthis way it won;t add it to a pre-existing (or create and add) JSONArray, but add it as a key to the JSONObject like this:

而不是accumulate使用put这种方式,它不会将它添加到预先存在的(或创建和添加)JSONArray,而是将其添加为 JSONObject 的键,如下所示:

JSONArray array = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("test", array);
System.out.println(obj.toString());

and now it'll print {"test":[]}

现在它会打印 {"test":[]}

回答by Ezhil V

That is because in the accumulatemethod,

那是因为在accumulate方法中,

Object object = this.opt(key); //gets the key value. Null in your case.
if (object == null) {
    this.put(key,
        value instanceof JSONArray ? new JSONArray().put(value) : value);
}

This is as per the API which clearly says (for the accumulatemethod) -

这是根据 API 明确说明的(对于accumulate方法)-

Accumulate values under a key. It is similar to the put method except that if there is already an object stored under the key then a JSONArray is stored under the key to hold all of the accumulated values. If there is already a JSONArray, then the new value is appended to it. In contrast, the put method replaces the previous value. If only one value is accumulated that is not a JSONArray, then the result will be the same as using put. But if multiple values are accumulated, then the result will be like append.

在一个键下累积值。它类似于 put 方法,不同之处在于如果已经有一个对象存储在键下,那么 JSONArray 存储在键下以保存所有累积值。如果已经有一个 JSONArray,那么新值会附加到它上面。相比之下, put 方法替换了先前的值。如果仅累积一个不是 JSONArray 的值,则结果将与使用 put 相同。但是如果累加了多个值,那么结果就像append一样。

You can use put()as mentioned in the other answer, for your desired result.

您可以put()按照其他答案中的说明使用,以获得所需的结果。