简体   繁体   English

使用org.json在java中创建JSON

[英]Creating JSON in java using org.json

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":[[]]}

instead of using accumulate use put this 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这种方式赢得了; t将其添加到一个预先存在(或创建并添加)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":[]}

That is because in the accumulate method, 那是因为在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 accumulate method) - 这是根据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. 它与put方法类似,只是如果已经有一个对象存储在键下,则JSONArray存储在键下以保存所有累积值。 If there is already a JSONArray, then the new value is appended to it. 如果已经存在JSONArray,则将新值附加到其上。 In contrast, the put method replaces the previous value. 相反,put方法替换了先前的值。 If only one value is accumulated that is not a JSONArray, then the result will be the same as using put. 如果只累积了一个不是JSONArray的值,那么结果将与使用put相同。 But if multiple values are accumulated, then the result will be like append. 但是如果累积了多个值,那么结果就像追加一样。

You can use put() as mentioned in the other answer, for your desired result. 您可以使用另一个答案中提到的put()来获得所需的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM