Android 使用Gson解析json案例详解

一、目前解析json有三种工具:org.json(Java常用的解析),fastjson(阿里巴巴工程师开发的),Gson(Google官网出的),解析速度最快的是Gson,下载地址:https://code.google.com/p/google-gson/

二、什么是JSON:

JSON即JavaScript Object Natation, 它是一种轻量级的数据交换格式, 与XML一样, 是广泛被采用的客户端和服务端交互的解决方案.

三、JSON对象:

JSON中对象(Object)以”{“开始, 以”}”结束. 对象中的每一个item都是一个key-value对, 表现为”key:value”的形式, key-value对之间使用逗号分隔. 如:{“name”:”coolxing”, “age”=24, “male”:true, “address”:{“street”:”huiLongGuan”, “city”:”beijing”, “country”:”china”}}. JSON对象的key只能是string类型的, 而value可以是string, number, false, true, null, Object对象甚至是array数组, 也就是说可以存在嵌套的情况.

四、JSON数组:

JSON数组(array)以”[“开始, 以”]”结束, 数组中的每一个元素可以是string, number, false, true, null, Object对象甚至是array数组, 数组间的元素使用逗号分隔. 如[“coolxing”, 24, {“street”:”huiLongGuan”, “city”:”beijing”, “country”:”china”}].

五、Gson的基本使用方法:
通过获取JsonReader对象解析JSON数据:

String jsonData = "[{\"username\":\"arthinking\",\"userId\":001},{\"username\":\"Jason\",\"userId\":002}]";
try{
    JsonReader reader = new JsonReader(new StringReader(jsonData));
    reader.beginArray();
    while(reader.hasNext()){
        reader.beginObject();
        while(reader.hasNext()){
            String tagName = reader.nextName();
            if(tagName.equals("username")){
                System.out.println(reader.nextString());
            }
            else if(tagName.equals("userId")){
                System.out.println(reader.nextString());
            }
        }
        reader.endObject();
    }
    reader.endArray();
}
catch(Exception e){
    e.printStackTrace();
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

通过把JSON数据映射成一个对象,使用Gson对象的fromJson()方法获取一个对象数组进行操作:
创建JSON数据对应的一个POJO对象User.java:

public class User {
    private String username ;
    private int userId ;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

使用Gson对象获取User对象数据进行相应的操作:

Type listType = new TypeToken<LinkedList<User>>(){}.getType();
Gson gson = new Gson();
LinkedList<User> users = gson.fromJson(jsonData, listType);
for (Iterator iterator = users.iterator(); iterator.hasNext();) {
    User user = (User) iterator.next();
    System.out.println(user.getUsername());
    System.out.println(user.getUserId());
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

如果要处理的JSON字符串只包含一个JSON对象,则可以直接使用fromJson获取一个User对象:

String jsonData = "{\"username\":\"arthinking\",\"userId\":001}";
Gson gson = new Gson();
User user = gson.fromJson(jsonData, User.class);
System.out.println(user.getUsername());
System.out.println(user.getUserId());
 
 
  • 1
  • 2
  • 3
  • 4
  • 5

解析复杂实例:

数据格式:(对于格式比较乱json数据,我们可以使用HIJSON工具进行代码的格式化!)

{
    "data": {
        "partnerteamlist": [
            {
                "pteamId": 72825,
                "ptitle": "随摄影/共6套服装/准爸准妈共拍/免费肚画/底片全送。",
                "pteamprice": 288
            },
            {
                "pteamId": 72598,
                "ptitle": "随摄影/拍摄200张/4本相册/品质拍摄/送全新婚纱。",
                "pteamprice": 2888
            },
            {
                "pteamId": 72613,
                "ptitle": "随摄影/送全新婚纱/多外景拍摄/服装不限数量/绝无二次消费!",
                "pteamprice": 3699
            },
            {
                "pteamId": 72638,
                "ptitle": "随摄影/服装不限数量/高品质拍摄260张/送全新婚纱。",
                "pteamprice": 4299
            },
            {
                "pteamId": 72716,
                "ptitle": "随摄影/3组服装造型/内外景拍摄/完全透明消费!",
                "pteamprice": 388
            }
        ],
        "liketeamlist": [
            {
                "lteamId": 65886,
                "ltitle": "爱丽尔婚纱摄影/2本相册/6套服装造型/拍摄不限最低拍摄150张。",
                "limage": "http://img.pztuan.com/upfile/team/2013/0712/201307120257551465.jpg",
                "lteamprice": 518,
                "lmarketprice": 3999
            },
            {
                "lteamId": 57133,
                "ltitle": "陶冶摄影/婚纱闺蜜/6组服装造型/拍摄不低于120张!",
                "limage": "http://img.pztuan.com/upfile/team/2013/0628/201306281115249737.jpg",
                "lteamprice": 580,
                "lmarketprice": 3380
            }
        ],
        "feedbacks": {
            "feedbacklist": [
                {
                    "comment": "5分",
                    "createtime": "2014.07.08 13:38",
                    "score": 5,
                    "username": "l***2"
                }
            ],
            "totalcount": 1,
            "totalscore": 5
        }
    },
    "err": null,
    "state": 1
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61

实体类(里面的成员变量和接口的返回值名称一 一对应才能保证解析正确):

import java.util.List;

public class OtherDetail {

    private int state;
    private List<err> err;
    private OtherDetail2 data;

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }

    public List<err> getErr() {
        return err;
    }

    public void setErr(List<err> err) {
        this.err = err;
    }

    public OtherDetail2 getData() {
        return data;
    }

    public void setData(OtherDetail2 data) {
        this.data = data;
    }

    public class OtherDetail2 {
        private List<partnerteamlist> partnerteamlist;
        private List<liketeamlist> liketeamlist;
        private List<feedbacks> feedbacks;

        public List<liketeamlist> getLiketeamlist() {
            return liketeamlist;
        }

        public void setLiketeamlist(List<liketeamlist> liketeamlist) {
            this.liketeamlist = liketeamlist;
        }

        public List<feedbacks> getFeedbacks() {
            return feedbacks;
        }

        public void setFeedbacks(List<feedbacks> feedbacks) {
            this.feedbacks = feedbacks;
        }

        public class partnerteamlist {
            private int pteamId;
            private String ptitle;
            private Double pteamprice;

            public int getPteamId() {
                return pteamId;
            }

            public void setPteamId(int pteamId) {
                this.pteamId = pteamId;
            }

            public String getPtitle() {
                return ptitle;
            }

            public void setPtitle(String ptitle) {
                this.ptitle = ptitle;
            }

            public Double getPteamprice() {
                return pteamprice;
            }

            public void setPteamprice(Double pteamprice) {
                this.pteamprice = pteamprice;
            }

        }

        public class liketeamlist {
            private int lteamId;
            private String ltitle;
            private String limage;
            private Double lteamprice;
            private Double lmarketprice;

            public int getLteamId() {
                return lteamId;
            }

            public void setLteamId(int lteamId) {
                this.lteamId = lteamId;
            }

            public String getLtitle() {
                return ltitle;
            }

            public void setLtitle(String ltitle) {
                this.ltitle = ltitle;
            }

            public String getLimage() {
                return limage;
            }

            public void setLimage(String limage) {
                this.limage = limage;
            }

            public Double getLteamprice() {
                return lteamprice;
            }

            public void setLteamprice(Double lteamprice) {
                this.lteamprice = lteamprice;
            }

            public Double getLmarketprice() {
                return lmarketprice;
            }

            public void setLmarketprice(Double lmarketprice) {
                this.lmarketprice = lmarketprice;
            }
        }

        public class feedbacks {
            private int totalcount;
            private Double totalscore;
            private List<feedbacklist> feedbacklist;

            public int getTotalcount() {
                return totalcount;
            }

            public void setTotalcount(int totalcount) {
                this.totalcount = totalcount;
            }

            public Double getTotalscore() {
                return totalscore;
            }

            public void setTotalscore(Double totalscore) {
                this.totalscore = totalscore;
            }

            public List<feedbacklist> getFeedbacklist() {
                return feedbacklist;
            }

            public void setFeedbacklist(List<feedbacklist> feedbacklist) {
                this.feedbacklist = feedbacklist;
            }

            public class feedbacklist {
                private String username;
                private String comment;
                private String createtime;
                private Double score;

                public String getUsername() {
                    return username;
                }

                public void setUsername(String username) {
                    this.username = username;
                }

                public String getComment() {
                    return comment;
                }

                public void setComment(String comment) {
                    this.comment = comment;
                }

                public String getCreatetime() {
                    return createtime;
                }

                public void setCreatetime(String createtime) {
                    this.createtime = createtime;
                }

                public Double getScore() {
                    return score;
                }

                public void setScore(Double score) {
                    this.score = score;
                }

            }
        }

        public List<partnerteamlist> getPartnerteamlist() {
            return partnerteamlist;
        }

        public void setPartnerteamlist(List<partnerteamlist> partnerteamlist) {
            this.partnerteamlist = partnerteamlist;
        }
    }

    public class err {
        private int code;
        private String msg;

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232

注意上面内部类的运用。
解析:

Gson gson = new Gson();
OtherDetail d = gson.fromJson(jsonString,Detail.class);//取值的时候就从父类一层一层调子类成员(重要)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值