Android填坑系列:Android JSONObject 中对key-value为null的特殊处理

在与服务端通过JSON格式进行交互过程中,不同版本的JSON库在对于key-value为null情况上的处理不同。

Android自带的org.json对key-value都要求不能为null,对于必传的字段需要留意一下,尤其是留意value是否可能出现null的情形。否则导致服务端解析出现问题。

此坑已被踩中,留下小记。下面直接看一下相应位置源码:

 1 public class JSONObject {
 2 
 3     ......
 4 
 5     /**
 6      * Maps {@code name} to {@code value}, clobbering any existing name/value
 7      * mapping with the same name. If the value is {@code null}, any existing
 8      * mapping for {@code name} is removed.
 9      *
10      * @param value a {@link JSONObject}, {@link JSONArray}, String, Boolean,
11      *     Integer, Long, Double, {@link #NULL}, or {@code null}. May not be
12      *     {@link Double#isNaN() NaNs} or {@link Double#isInfinite()
13      *     infinities}.
14      * @return this object.
15      */
16     public JSONObject put(String name, Object value) throws JSONException {
17         if (value == null) {
18             nameValuePairs.remove(name);
19             return this;
20         }
21         if (value instanceof Number) {
22             // deviate from the original by checking all Numbers, not just floats & doubles
23             JSON.checkDouble(((Number) value).doubleValue());
24         }
25         nameValuePairs.put(checkName(name), value);
26         return this;
27     }
28     
29     
30     String checkName(String name) throws JSONException {
31         if (name == null) {
32             throw new JSONException("Names must be non-null");
33         }
34         return name;
35     }
36     
37     
38     ......
39     
40 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值