【问题标题】:Creating JSON in java using org.json使用 org.json 在 java 中创建 JSON
【发布时间】:2013-04-29 05:30:50
【问题描述】:

我正在尝试使用 org.json 库在 java 中创建一个 json 字符串,下面是代码 sn-p。

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

我希望它会打印出来

{"test":[]} 

在打印时

{"test":[[]]}

【问题讨论】:

标签: java json org.json


【解决方案1】:

不要使用accumulate,而是使用put,这样它不会;不会将它添加到预先存在的(或创建并添加)JSONArray,而是像这样将它作为键添加到 JSONObject:

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

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

【讨论】:

    【解决方案2】:

    那是因为在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);
    }
    

    这是按照 API 明确说明的(对于 accumulate 方法)-

    在一个键下累积值。它类似于 put 方法,除了 如果密钥下已经存储了一个对象,那么 JSONArray 存储在 key 下,用于保存所有的累积 价值观。如果已经有一个 JSONArray,那么新值为 附加到它。相比之下,put 方法替代了前面的 价值。如果只累积了一个不是 JSONArray 的值,则 结果将与使用 put 相同。但是如果有多个值 积累,那么结果会像追加一样。

    您可以使用其他答案中提到的put(),以获得您想要的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-12
      相关资源
      最近更新 更多