在與服務端通過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 }