import org.json.JSONArray;
import org.json.JSONException;import org.json.JSONObject;
這是Android原生的Json數據解析包,雖然沒有Gson和fastjson好用。
不過它很輕量,並不需要添加別的jar包,可以爲應用節省下小部分空間,利弊各有。
項目中有很多跟js進行交互的地方,傳遞數據時發現根本無法使用Object跟List<T>,於是就想到了Json。
Android跟js都把數據轉換成Json字符串,傳遞後再各自進行解析。
查了些資料,覺得有幾個地方還挺值得記錄一下。
解析Json就不再多言,遍地都是,隨便查查就能明白,我要說的是數據轉換成Json。
1、把對象轉換成Json字符串。
2、把字符數組轉換成Json字符串。
3、把Object數組轉換成Json字符串。
4、在JSONObject中添加Array。
1、把對象轉換成Json字符串
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", obj.getId());
jsonObject.put("url", obj.getUrl());
jsonObject.toString();
2、把字符數組轉換成Json字符串。
JSONArray jsonArray = new JSONArray();
jsonArray.put(string[0]);
jsonArray.put(string[1]);
jsonArray.put(string[2]);
jsonArray.toString();
3、把Object數組轉換成Json字符串。
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("id", obj.getId());
jsonObject1.put("url", obj.getUrl());
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("id", obj.getId());
jsonObject2.put("url", obj.getUrl());
jsonArray.put(jsonObject);
jsonArray.toString();
4、在JSONObject中添加Array。
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("id", obj.getId());
obj.put("url", obj.getUrl());
jsonArray.put(obj);
jsonObject.put("array", jsonArray);
jsonObject.toString();
不過再怎麼複雜也都是幾種情況相符組合一下而已。
祝君代碼永無BUG!!!