这里主要讲解的是使用Google提供的Gson API解析Json数据。
在使用Gson解析Json数据的过程中,
首先我们要New一个实体类:
/** * @author gongchaobin * * 书架上书本实体类 */ public class ShelfBook implements Serializable{ private String title;//书本标题 private String size;//资源大小 private String picurl;//书本封面URL private String DataUrl;//数据下载地址 private String key; private static final long serialVersionUID = 1L; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getPicurl() { return picurl; } public void setPicurl(String picurl) { this.picurl = picurl; } public String getDataUrl() { return DataUrl; } public void setDataUrl(String DataUrl) { this.DataUrl = DataUrl; } }
然后调用Gson API直接解析
public class JsonParser { private static final String TAG = JsonParser.class.getSimpleName(); public static JsonParser instance; private JsonParser(){ super(); } public static JsonParser getInstance(){ if (instance == null) { synchronized (JsonParser.class) { if (instance == null) { instance = new JsonParser(); } } } return instance; } public ShelfBook getShelfBook(String json) { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); ShelfBook result = gson.fromJson(json, ShelfBook.class); return result; } }
碰到一个JSONArray数组 我们还需要进行一些转化
注明:序列化的过程中区别成员变量的大小写
try { JSONArray jsonArray = new JSONArray(result); for(int i=0;i<jsonArray.length();i++){ JSONObject jsonObject = (JSONObject) jsonArray.get(i); ShelfBook shelfBook = JsonParser.getInstance().getShelfBook(jsonObject.toString()); Log.i(TAG, "title= " + shelfBook.getTitle()); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }