【重拾Android】(1)使用gson解析json数据

废话不多说,先来看一下复杂json格式的数据

{
    "data": {
        "picsize": "",
        "blogs": [
            {
                "photo_id": 19569850,
                "unm": "XXXXL桔子",
                "uid": 3149731,
                "cmts": [
                    {
                        "ava": "http://img4.duitang.com/uploads/files/201312/19/20131219204737_XVinc.jpeg",
                        "cont": "喜欢",
                        "id": 2445206,
                        "name": "巴黎-卢浮宫"
                    },
                    {
                        "ava": "http://img4.duitang.com/uploads/people/201311/16/20131116083610_BCeyB.thumb.24_24_c.jpeg",
                        "cont": "真的好棒>O<",
                        "id": 1948213,
                        "name": "雪糕冻儿"
                    }
                ],
                "good": false,
                "common": false,
                "price": 0,
                "rid": 169557009,
                "buylnk": "",
                "zanc": 8,
                "sta": 0,
                "ava": "http://img5.duitang.com/uploads/people/201407/15/20140715173822_yEt4L.thumb.24_24_c.jpeg",
                "coupon_price": 0,
                "albnm": "家居创意",
                "iwd": 500,
                "iht": 674,
                "albid": 58736725,
                "favc": 127,
                "tid": null,
                "ruid": 3149731,
                "id": 169557009,
                "repc": 2,
                "isrc": "http://img4.duitang.com/uploads/blog/201407/24/20140724140503_df2Wr.thumb.224_0.jpeg",
                "msg": "这是一对平时工作忙碌的夫妇第二个家,他们特别喜爱水,这间度假别墅让他们的身心得以放松,在这里像在云端畅游一般。粗犷休闲的装饰使得环境变得更加轻松。门前的阶梯把人引向户外生活,湖泊、小树林围绕这个开放而轻松的别墅,屋内陈设让其更加熠熠生辉。"
            },
            {
                "photo_id": 19569828,
                "unm": "XXXXL桔子",
                "uid": 3149731,
                "cmts": [],
                "good": false,
                "common": false,
                "price": 0,
                "rid": 169556836,
                "buylnk": "",
                "zanc": 2,
                "sta": 0,
                "ava": "http://img5.duitang.com/uploads/people/201407/15/20140715173822_yEt4L.thumb.24_24_c.jpeg",
                "coupon_price": 0,
                "albnm": "家居创意",
                "iwd": 500,
                "iht": 348,
                "albid": 58736725,
                "favc": 35,
                "tid": null,
                "ruid": 3149731,
                "id": 169556836,
                "repc": 0,
                "isrc": "http://img4.duitang.com/uploads/blog/201407/24/20140724140442_xrneS.thumb.224_0.jpeg",
                "msg": "国外度假别墅"
            }
        ],
        "hasrp": true,
        "has_next": true,
        "pgsource": "ad_",
        "first_blog": {
            "photo_id": 19569850,
            "unm": "XXXXL桔子",
            "uid": 3149731,
            "cmts": [
                {
                    "ava": "http://img4.duitang.com/uploads/files/201312/19/20131219204737_XVinc.jpeg",
                    "cont": "喜欢",
                    "id": 2445206,
                    "name": "巴黎-卢浮宫"
                },
                {
                    "ava": "http://img4.duitang.com/uploads/people/201311/16/20131116083610_BCeyB.thumb.24_24_c.jpeg",
                    "cont": "真的好棒>O<",
                    "id": 1948213,
                    "name": "雪糕冻儿"
                }
            ],
            "good": false,
            "common": false,
            "price": 0,
            "rid": 169557009,
            "buylnk": "",
            "zanc": 8,
            "sta": 0,
            "ava": "http://img5.duitang.com/uploads/people/201407/15/20140715173822_yEt4L.thumb.24_24_c.jpeg",
            "coupon_price": 0,
            "albnm": "家居创意",
            "iwd": 500,
            "iht": 674,
            "albid": 58736725,
            "favc": 127,
            "tid": null,
            "ruid": 3149731,
            "id": 169557009,
            "repc": 2,
            "isrc": "http://img4.duitang.com/uploads/blog/201407/24/20140724140503_df2Wr.thumb.224_0.jpeg",
            "msg": "这是一对平时工作忙碌的夫妇第二个家,他们特别喜爱水,这间度假别墅让他们的身心得以放松,在这里像在云端畅游一般。粗犷休闲的装饰使得环境变得更加轻松。门前的阶梯把人引向户外生活,湖泊、小树林围绕这个开放而轻松的别墅,屋内陈设让其更加熠熠生辉。"
        },
        "coupon": false,
        "nopth": true
    },
    "success": true
}


看似复杂,但是解析起来并不困难,由于我们只需要"blogs"里面的数据,所以我们要先建立数据实体类,数据实体类中并不是每个属性都需要有,这里只选用我们需要用到的属性。


public class PhotoInfo implements Serializable{
 
 private String photo_id;
 private String isrc;
 private String msg;
 private int iwd;
 private int iht;
 
 public String getPhoto_id() {
  return photo_id;
 }
 public void setPhoto_id(String photo_id) {
  this.photo_id = photo_id;
 }
 public String getIsrc() {
  return isrc;
 }
 public void setIsrc(String isrc) {
  this.isrc = isrc;
 }
 public String getMsg() {
  return msg;
 }
 public void setMsg(String msg) {
  this.msg = msg;
 }
 public int getIwd() {
  return iwd;
 }
 public void setIwd(int iwd) {
  this.iwd = iwd;
 }
 public int getIht() {
  return iht;
 }
 public void setIht(int iht) {
  this.iht = iht;
 }
}


解析过程如下:


//json是json格式的String
SONObject newsObject = new JSONObject(json);
           
//解嵌套,获取data中的数据,这里面只有一个数据
JSONObject jsonObject = newsObject.getJSONObject("data");
//解嵌套,获取blogs中的数据,注意这里是多个数据
JSONArray blogsJson = jsonObject.getJSONArray("blogs");
                       
//泛型
Type listType = new TypeToken<LinkedList<PhotoInfo>>(){}.getType();
Gson gson = new Gson();
//将blogsJson转化成String并解析即可
ps = gson.fromJson(blogsJson.toString(), listType);


因为数据较复杂,我这里先使用 JSONObject进行解嵌套,再使用Gson通过反射直接生成对象,简单方便, 也可以直接通过嵌套定义的类来生成对象。如下所示:

JSON格式数据
{
    "user_get_response": {
        "user": {
            "buyer_credit": {
                "good_num": 0,
                "level": 0,
                "score": 0,
                "total_num": 0
            },
            "created": "2009-09-30 13:15:54",
            "last_visit": "2009-12-22 13:31:58",
            "location": {},
            "nick": "sandbox_c_23",
            "seller_credit": {
                "good_num": 0,
                "level": 0,
                "score": 0,
                "total_num": 0
            }
        }
 }

JAVA代码

class Address {
    String street;
    String city;
    String province;
    String country;
    
    public Address() {};
    
    public String toString() {return street;}
}

class CreditInfo {
    int good_num;
    int level;
    int score;
    int total_num;
    
    public CreditInfo() {};
    
    public String toString() {
        return String.format("[good_num: %1$s, level: %2$s, score: %3$s, total_num: %4$s]", good_num, level, score, total_num);
    }
}

class User {
    CreditInfo buyer_credit;
    Date created;
    Date last_visit;
    Address location;
    String nick;
    CreditInfo seller_credit;
    public User() {buyer_credit=new CreditInfo(); seller_credit=new CreditInfo();}
    public String toString() {
        return String.format("buyer_credit: %1$s, \ncreated: %2$s, \nlast_visit: %3$s, \nlocation: %4$s, \nnick: %5$s, \nseller_credit: %6$s", 
            buyer_credit,
            created,
            last_visit,
            location,
            nick,
            seller_credit);
    }
}

class UserResponse {
    User user;
    public UserResponse() {}
    public String toString() {return "user = " + user;}
}

class Response {
    UserResponse user_get_response;
    public Response() {}
    public String toString() {return user_get_response.toString();}
}

public class Test {
    
    public static void main(String[] args) {
        String s = "{\"user_get_response\":{\"user\":{\"buyer_credit\":{\"good_num\":0,\"level\":0,\"score\":0,\"total_num\":0},\"created\":\"2009-09-30 13:15:54\",\"last_visit\":\"2009-12-22 13:31:58\",\"location\":{},\"nick\":\"sandbox_c_23\",\"seller_credit\":{\"good_num\":0,\"level\":0,\"score\":0,\"total_num\":0}}}}";
        Gson gson = new Gson();
        Response r = gson.fromJson(s, Response.class);
        System.out.println(r);
    }
}




{
    "total": 100,
    "rows": [
        {
            "key": "key1",
            "value": "value1"
        },
        {
            "key": "key2",
            "value": "value2"
        }
    ]
}

  1. public class A{  
  2.   public string key;  
  3.   public string value;  
  4.  }  
  5.   
  6. public class B {  
  7.  public int total;  
  8.  public List<A> rows;  
  9. }  
  1. Type type = new TypeToken<B>().getType();  
  2. Gson gson = new Gson();  
  3. B b = gson.fromJson(json, type);  

参考链接:
http://www.cnblogs.com/jxgxy/p/3677256.html




 




你可能感兴趣的:(【重拾Android】(1)使用gson解析json数据)