java - 无法将空值放入 JSON 对象

标签 java android json

我正在尝试使用 JSON 将参数传递给 api。

class Sample
{ ...
   String token;
...

void method()
{ ...
    JSONObject params = new JSONObject();
    params.put(KEY_TOKEN,token);
    params.put(KEY_DATE,date);

    Log.e("params ",params+"");


      ...  }    

我将 params 的值作为 {"date":"2017-06-19"} 但无处可见 token 。 我还没有初始化 token ,它的值是 null 作为它的一个实例变量。那么是不是没有包含未初始化的值呢?

最佳答案

就在 the documentation 中, 在第一段中:

Values may not be null, NaNs, infinities, or of any type not listed here.

所以是的,它是 “......null 值不包括在内的东西......” (编辑:这是你原来的引述问题;您更新后的问题将其更改为“未初始化的值”,但对象引用的默认值为 null,所以...)

不过,这是该类的一个“特性”; JSON本身理解 null 就好了。在文档的更下方,它说您使用了“重要值(value)”,NULL , 代表 null。这看起来……很奇怪。有一个关于它的注释:

Warning: this class represents null in two incompatible ways: the standard Java null reference, and the sentinel value NULL. In particular, calling put(name, null) removes the named entry from the object but put(name, JSONObject.NULL) stores an entry whose value is JSONObject.NULL.

所以:

params.put(KEY_TOKEN, token == null ? JSONObject.NULL : token);

关于java - 无法将空值放入 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44631604/

相关文章:

java - 如何在 Java 中重置迭代器?

php - 使用 php 和 android 连接到 mysql 时出现 NullPointerException

java - Android 中的 TextView 在右侧留下间隙。这个要怎么调整

php - 将 JSON 字符串解析为数组,而不是对象

帖子上的 JavaScript ajax 警报不起作用

Java CSV 读取器/写入器问题

java - while循环使小程序白屏且无响应

java - Spring JPA @事务原子

Android:具有自动完成功能的多选列表首选项?

javascript - 如何映射不同 svg 组件的列表?