我正在try 使用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"},但找不到令牌.

推荐答案

Right there in the documentation, in the first paragraph:

值不能为nullNaNs、无穷大或此处未列出的任何类型.

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

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:

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);

Json相关问答推荐

如何在数组抖动中按值分组

由于无效的UTF-8开始字节0xa0,JSON被拒绝,但编码似乎有效

在Zig中解析JSON失败

将 REST API - json 输出转换为表 Power BI

使用 Power BI 中的 Deneb 视觉效果绘制面积图中的 X 轴日期

为什么解析的字典相等而腌制的字典不相等?

在 Perl Mojolicious 中呈现 JSON 时防止转义字符

如何对使用转换器的 Grails 服务进行单元测试?

ASP.NET MVC - 将 Json 结果与 ViewResult 结合起来

JSON RPC - 什么是id?

Retrofit 2.0 如何解析嵌套的 JSON 对象?

数据包含连续问号时无法理解的 jQuery $.ajax() 行为

JSON Schema:验证数字或空值

使用 application/json 优于 text/plain 的优势?

IE10/11 Ajax XHR 错误 - SCRIPT7002:XMLHttpRequest:网络错误 0x2ef3

使用 JSON.NET 序列化/反序列化对象字典

如何在所有子项中查询具有特定值的属性的firebase

play 2 JSON 格式中缺少的属性的默认值

如何将字符串转换为 JsonObject

使用 PHP 将 CSV 转换为 JSON