简体   繁体   English

Java创建带有空值的JSONObject作为JSONObject

[英]Java create JSONObject with empty value as JSONObject

I'm trying to create an JSONObject with a specific key and empty value. 我正在尝试创建具有特定键和空值的JSONObject。 But the value should be a JSONObject and not a JSONArray. 但是该值应该是JSONObject,而不是JSONArray。

I already tried it with localJson.append(key, JSONObject.NULL); 我已经尝试过使用localJson.append(key, JSONObject.NULL); or localJson.append(key, new JSONObject()); localJson.append(key, new JSONObject()); . Each time the value is a JSONArray with the value[0] = null or just [{}] 每次该值是一个JSONArray,其value[0] = null或仅是[{}]

Is there any way to make it a JSONObject? 有什么办法可以使其成为JSONObject吗?

Using org.codehaus.jettison.json.JSONObject : 使用org.codehaus.jettison.json.JSONObject

Use public JSONObject put(String key, Object value) instead of append method. 使用public JSONObject put(String key, Object value)代替append方法。

Your code isn't working because method JSONObject append(String key, Object value) is defined as follows: 您的代码无法正常工作,因为方法JSONObject append(String key, Object value)的定义如下:

public JSONObject append(String key, Object value) throws JSONException {
    testValidity(value);
    Object o = opt(key);
    if (o == null) {
        put(key, new JSONArray().put(value));
    } else if (!(o instanceof JSONArray)){
        throw new JSONException("JSONObject[" + key + "] is not a JSONArray.");
    } else {
        put(key, new JSONArray().put(o).put(value));
    }
    return this;
}

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

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