java JSONObject.append into object - 结果是嵌套数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11297200/
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 04:33:53  来源:igfitidea点击:

JSONObject.append into object - result is nested array?

javajson

提问by Suma

Following code produces a nested array as a result for keys containing three items:

以下代码为包含三个项目的键生成一个嵌套数组:

import org.codehaus.jettison.json.JSONObject;
// ...

JSONObject ret = new JSONObject();
for (Key key:keys) ret.append("blocked",key.id());

The result is:

结果是:

{"blocked": [[["1"],"2"],"3"]}

Is this expected? If it is, how can I construct a plain array adding item by item?

这是预期的吗?如果是,我如何构建一个逐项添加的普通数组?

回答by legege

You need to create a JSONArrayobject:

您需要创建一个JSONArray对象:

JSONObject ret = new JSONObject();
JSONArray arr = new JSONArray();
arr.put("1");
arr.put("2");
arr.put("3");
ret.put("blocked", arr);

The result is:

结果是:

{"blocked":["1","2","3"]}

回答by Thomas

It's curious because the API says the following:

这很奇怪,因为API 说明如下

Append values to the array under a key. If the key does not exist in the JSONObject, then the key is put in the JSONObjectwith its value being a JSONArraycontaining the value parameter. If the key was already associated with a JSONArray, then the value parameter is appended to it.

将值附加到键下的数组。如果该键不存在于 中 JSONObject,则该键被放入 中JSONObject,其值为 JSONArray包含 value 参数的 a。如果键已经与 a 关联JSONArray,则 value 参数会附加到它。

But it doesn't work correctly. When I do:

但它不能正常工作。当我做:

JSONObject o = new JSONObject();
o.append("arr", "123");
o.append("arr", "456");

I get an Exception saying that "JSONObject[arr] is not a JSONArray". It looks like there is a bug.

我收到一个异常,说“ JSONObject[arr] is not a JSONArray”。看起来有一个错误。

回答by buttonius

I ran into a similar problem. You should use the putmethod; not the appendmethod. And, of course, you should create a JSONArrray and use that as the second argument of the putmethod.

我遇到了类似的问题。你应该使用put方法;不是append方法。当然,您应该创建一个 JSONArrray 并将其用作put方法的第二个参数。