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 }

 

posted @ 2016-05-13 20:56  HappyCorn  阅读(7475)  评论(0编辑  收藏  举报