对于 服务器返回的数据
result={"limit":20,"total":5,"start":1,"item":[{"appSize":"","categoryId":"","categoryName":"","commission":"","imageUrl":"upload/product/20140729195155.jpg","is3G":"0","productId":"441","productName":"5元闲时流量包","productPrice":"","recNum":""},{"appSize":"","categoryId":"","categoryName":"","commission":"","imageUrl":"upload/product/20140729195315.jpg","is3G":"0","productId":"442","productName":"15元闲时流量包","productPrice":"","recNum":""},{"appSize":"","categoryId":"","categoryName":"","commission":"","imageUrl":"upload/product/20140624100105.png","is3G":"0","productId":"00000010","productName":"10元闲时流量包","productPrice":"","recNum":""},{"appSize":"","categoryId":"","categoryName":"","commission":"10","imageUrl":"upload/product/20140624100105.png","is3G":"0","productId":"00000001","productName":"3G用户100M流量包","productPrice":"","recNum":""},{"appSize":"","categoryId":"","categoryName":"","commission":"","imageUrl":"http://192.168.2.171:8080/upfiles/upload/product/20140827180416.jpg","is3G":"0","productId":"00000002","productName":"3G用户300M流量包","productPrice":"","recNum":""}],
"resultCode":"0"} 该怎么解析呢???
方法一:(这种方法适用于相对简单的json串解析)
JSONObject json = new JSONObject(responseInfo.result);
String code = json.getString("resultCode");
对也Item里面的内容的解析
List<ProductInfoBean> list = new ArrayList<ProductInfoBean>();
JSONArray items = json.getJSONArray("item");
for(int i = 0; i < items.length(); i++){
JSONObject jsonObject = (JSONObject) items.opt(i);
ProductInfoBean ob = new ProductInfoBean();
ob.setProductCode(jsonObject.getString("productId"));
ob.setProductName(jsonObject.getString("productName"));
ob.setCommission(jsonObject.getString("commission"));
ob.setEffectFlag(jsonObject.getString("effectFlag"));
ob.setIs3G(jsonObject.getString("is3G"));
ob.setProductImageUrl(jsonObject.getString("imageUrl"));
list.add(ob);
}
方法二:Gson解析(这种方法适用于相对复杂的json串解析)
首先导入Gson.jar包,百度搜索下载并导入工程项目;
首先我们需要定义一个序列化的Bean,这里采用内部类的形式,这样比较容易看得清晰些:
- public class MyBean {
- public String limit;
- public String total;
- public String start;
- public String resultCode;
- public String total;
- public List<Item > item;
- public static class Item {
- public String appSize;
- public String categoryId;
- public String categoryName;
- public String commission;
- public String imageUrl;
- public String is3G;
- public String productId;
- public String productName;
- public String productPrice;
- public String recNum;
- }
- }
很多时候大家都是不知道这个Bean是该怎么定义,这里面需要注意几点:
1、内部嵌套的类必须是static的,要不然解析会出错;
2、类里面的属性名必须跟Json字段里面的Key是一模一样的;
3、内部嵌套的用[]括起来的部分是一个List,所以定义为 public List<Item> item,
具体的大家对照Json字符串看看就明白了,不明白的我们可以互相交流,本人也是新手!
接下来就很简单了:
- Gson gson = new Gson();
- MyBean myBean = gson.fromJson(result, MyBean.class);
希望能看得明白!