Json數據
這里附上一個檢查json數據格式是否正確的網站http://www.json.cn/
三種解析方式android自帶解析,Gson解析,FastJson解析
1、android自帶解析
json_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String s = getString(); Log.d("txt",s); List<City> list = new ArrayList<City>(); try { JSONArray obj = new JSONArray(s); for(int i=0;i<obj.length();i++){ JSONObject jsonobj = (JSONObject)obj.get(i); City city = new City(); city.setCode(jsonobj.getString("code")); city.setSheng(jsonobj.optString("sheng")); city.setDi(jsonobj.optString("di")); city.setXian(jsonobj.optString("xian")); city.setName(jsonobj.optString("name")); city.setLevel(jsonobj.optInt("level")); Log.d("txt",city.toString()); textView.append(city.toString()); } } catch (JSONException e) { e.printStackTrace(); } } });先獲取JSON數組,在解析JsonObject。
2、Gson解析
Gson_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String s = getString(); JsonParser parser = new JsonParser(); JsonArray jsonArray = parser.parse(s).getAsJsonArray(); Gson gson = new Gson(); for (JsonElement obj:jsonArray){ City city = gson.fromJson(obj,City.class); Log.d("txt", city.toString()); textView.append(city.toString()); } } });先獲取Json數組,再解析jsonObject。
3、FastJson
fastjson_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String s = getString(); Log.d("txt",s); List<City> lists = JSON.parseArray(s,City.class); for(City city:lists){ textView.append(city.toString()); Log.d("txt",city.toString()); } } });直接獲取JsonArray解析List<Bean>。
public static final Object parse(String text); // 把JSON文本parse為JSONObject或者JSONArray public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject public static final <T> T parseObject(String text, Class<T> clazz); // 把JSON文本parse為JavaBean public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray public static final <T> List<T> parseArray(String text, Class<T> clazz); //把JSON文本parse成JavaBean集合 public static final String toJSONString(Object object); // 將JavaBean序列化為JSON文本 public static final String toJSONString(Object object, boolean prettyFormat); // 將JavaBean序列化為帶格式的JSON文本
public static final Object toJSON(Object javaObject); 將JavaBean轉換為JSONObject或者JSONArray(和上面方法的區別是返回值是不一樣的)
三種解析方法,個人感覺fastjson使用起來還是很方便的。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答