java - 如何在 java 中使用 org.json.JSONObject 将值设置为 null?

标签 java json

如何在 java 中使用 org.json.JSONObject 将值设置为 null?我当然可以通过使用 isNull 读取值是否为 null - 但似乎当我输入 null 时,它只是忽略了我:

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:

A sentinel value used to explicitly define a name with no value. Unlike null, names with this value:

  • 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.

This value violates the general contract of equals(Object) by returning true when compared to null. Its toString() method returns "null".

关于java - 如何在 java 中使用 org.json.JSONObject 将值设置为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13613754/

相关文章:

javascript - 在for循环javascript之外访问数组变量

java - 反序列化 json,将子类对象提升到顶层而不是嵌套类

java - 运行时类路径中是否需要注解类文件?

java - JVM什么时候加载注解类

java - Netty - getRemoteAddress 每次返回不同的端口

java - 使用访问者模式的树转换

javascript - 如何从 puppeteer 抓取表中输出正确的 json?

java - 基于类反序列化json时发生异常,该类内部有一个接口(interface)类型

c# - 我将如何使用字典解析此 JSON?

java - 使用 JDBC 提示输入用户名/密码 : where is that prompt coming from and where do my properties go?