使用JSON对象中的空值

时间:2012-01-16 23:19:05

标签: android json

我正在调用服务器,该服务器可以按以下格式返回键值映射:

{...
 "mykey":null
...}

我能够从上面创建一个JSONObject实例(使用JSONObject(String json)构造函数)但是我不确定如何确定这个JSONObject实例是否有“mykey”的映射,并且映射的值是null?以下检查是否会这样做......

myJSONObject.has("mykey") && !myJSONObject.isNull("mykey")

......或者有更好的方法吗?特别是,我对JSONObject.NULL对象是否与null的含义相同感到困惑?

另外:以及获取映射的值为null的键,我需要创建映射null的JSONObject实例钥匙。会...

myJSONObject.put("mykey", JSONObject.NULL);

......做这个工作,还是我还有另一种方法呢?

2 个答案:

答案 0 :(得分:2)

如果您正在使用内置的Android JSON库,那么您实际上正在使用org.json中的(功能强大的)库。

https://github.com/douglascrockford/JSON-java

如果是这种情况,我们可以通过grep代码来查看大部分答案。

  

特别是,我对JSONObject.NULL对象是否与null相同感到困惑?

这应该有希望帮助:

/**
 * JSONObject.NULL is equivalent to the value that JavaScript calls null,
 * whilst Java's null is equivalent to the value that JavaScript calls
 * undefined.
 */
 private static final class Null {

    /**
     * There is only intended to be a single instance of the NULL object,
     * so the clone method returns itself.
     * @return     NULL.
     */
    protected final Object clone() {
        return this;
    }

    /**
     * A Null object is equal to the null value and to itself.
     * @param object    An object to test for nullness.
     * @return true if the object parameter is the JSONObject.NULL object
     *  or null.
     */
    public boolean equals(Object object) {
        return object == null || object == this;
    }

    /**
     * Get the "null" string value.
     * @return The string "null".
     */
    public String toString() {
        return "null";
    }
}

/**
 * It is sometimes more convenient and less ambiguous to have a
 * <code>NULL</code> object than to use Java's <code>null</code> value.
 * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>.
 * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>.
 */
public static final Object NULL = new Null();

第2部分:

  

我不确定如何确定此JSONObject实例是否具有   映射“mykey”并且映射的值为null?将   以下检查做...

myJSONObject.has("mykey") && !myJSONObject.isNull("mykey")
是的 - 这似乎与任何方法一样好。特别是,您希望使用isNull方法检查null,因为JSONObject定义了它自己的NULL对象(参见上文)。

  

另外:以及获取值可以的键的映射   null,我需要创建将null映射到键的JSONObject实例。   会...

     

myJSONObject.put(“mykey”,JSONObject.NULL); ......做这个工作,或者是   我应该采取另一种方式吗?

这正是你想要做的 - 特别是使用JSONObject.NULL而不是java的null(见上文)。

答案 1 :(得分:1)

查看API文档。

boolean has(String name)
         Returns true if this object has a mapping for name.

boolean isNull(String name)
         Returns true if this object has no mapping for name or if it has a mapping whose value is NULL.

如果你不确定序列化器/解串器的行为,你总是可以用简单的代码片段来测试输出/解析结果。