无法在JSON对象中放入空值 [英] Unable to put null values in JSON object
问题描述
我正在尝试使用JSON将参数传递给api.
I am trying to pass parameter to api using JSON.
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"}
,但没有地方看到令牌.
我尚未初始化令牌,并且其值为null作为其实例变量.难道没有包含未初始化的值吗?
I get the value of params as {"date":"2017-06-19"}
but token is seen nowhere.
I have not initialized token and its value is null as its an instance variable. So is it something that uninitialized value are not included?
推荐答案
文档,在第一段中:
值不能为
null
,NaN
,无穷大或此处未列出的任何类型.
Values may not be
null
,NaN
s, infinities, or of any type not listed here.
是的,这是"...一些不包含null
值的东西..." (这是您原始问题的引文;您已更新的问题将其更改为未初始化的值",但对象引用的默认值为null
,所以...)
So yes, it is "...something that null
values are not included..." (edit: that was a quote from your original question; your updated question changes it to "uninitialized values" but the default value of an object reference is null
, so...)
这是该类的功能"; JSON 本身可以理解null
.在文档的更下方,它说您使用了正弦值", null
.似乎...很奇怪.有一个关于它的注释:
It's a "feature" of that class, though; JSON itself understands null
just fine. Further down in the documentation it says you use a "sentinal value," NULL
, to represent null
. Which seems...odd. There's a note about it:
警告:此类以两种不兼容的方式表示
null
:标准Javanull
引用和标记值NULL
.特别是,调用put(name, null)
会从对象中删除命名的条目,但是put(name, JSONObject.NULL)
会存储一个值为JSONObject.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);
这篇关于无法在JSON对象中放入空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!