如何在java中使用org.json.JSONObject将值设置为null?
问题描述:
如何在java中使用org.json.JSONObject将值设置为null?我当然可以通过使用isNull来读取值是否为null - 但似乎当我放置null时,它只是忽略了我:
How do you set a value to null with org.json.JSONObject in java? I can certainly read if a value is null by using isNull - but it seems like when I put null, it just ignores me:
JSONObject o = new JSONObject();
o.put("key",null);
o.isNull("key"); // returns true, buuuut...
o.has("key"); // returns false
o.isNull("somethingIHaventSetAtAll"); // also returns true, unfortunately
答
尝试设置 JSONObject.NULL
而不是 null
:
用于显式定义名称的sentinel值没有价值。与null不同,具有此值的名称:
A sentinel value used to explicitly define a name with no value. Unlike null, names with this value:
- 显示在names()数组中
- show在键()迭代器中
- 为has(String)返回true
- 不要抛出get(String)
- 包含在编码的JSON字符串中。
- show up in the names() array
- show up in the keys() iterator
- return true for has(String)
- do not throw on get(String)
- are included in the encoded JSON string.
与null相比,返回true时,此值违反了equals(Object)的常规协定。它的toString()方法返回null。
This value violates the general contract of equals(Object) by returning true when compared to null. Its toString() method returns "null".