我正在尝试使用 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
,NaN
s, 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 Javanull
reference, and the sentinel valueNULL
. In particular, callingput(name, null)
removes the named entry from the object butput(name, JSONObject.NULL)
stores an entry whose value isJSONObject.NULL
.
所以:
params.put(KEY_TOKEN, token == null ? JSONObject.NULL : token);
关于java - 无法将空值放入 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44631604/