原CSDN博客已弃用,文章会逐渐迁移过来。

转帖请注明本文出自weimeig的博客(https://blog.csdn.net/weimeig/article/details/80251365),请尊重他人的辛勤劳动成果,谢谢

添加依赖

build.gradle

dependencies {  
    compile 'com.google.code.gson:gson:2.4'  
}  

右上角Sync Now

AndroidStudio自带了将Json数据自动生成实体类的工具,详情可百度,这里不详述

初步入门案例1:

定义模拟的需要解析的数据

String cniao = "{\n" +  
                  "\"sites\": [\n" +  
                  "{ \"name\":\"菜鸟教程\" , \"url\":\"m.runoob.com\" }, \n" +  
                  "{ \"name\":\"google\" , \"url\":\"www.google.com\" }, \n" +  
                  "{ \"name\":\"微博\" , \"url\":\"www.weibo.com\" }\n" +  
                  "]\n" +  
                  "}";  

定义存放被解析的数据的实体类对象

cainiao.java

/** 
     * 存放被解析的数据的实体类对象 
     * cainiao.java 
     */  
    public static class cainiao{  
        private List<SitesBean> sites;  

        public List<SitesBean> getSites() {  
            return sites;  
        }  

        public void setSites(List<SitesBean> sites) {  
            this.sites = sites;  
        }  

        public static class SitesBean {  

            private String name;  
            private String url;  

            public String getName() {  
                return name;  
            }  

            public void setName(String name) {  
                this.name = name;  
            }  

            public String getUrl() {  
                return url;  
            }  

            public void setUrl(String url) {  
                this.url = url;  
            }  
        }  
    }  

数据解析

//参数1:网络请求所返还的需要解析的数据对象,参数2:要把数据解析到的实体类对象  
cainiao st= new Gson().fromJson(cniao,cainiao.class);  

强化练习案例2:
定义模拟的需要解析的数据

String login = "{\n" +  
                "    \"code\": \"200\",\n" +  
                "    \"info\": \"登录成功\",\n" +  
                "    \"data\": {\n" +  
                "        \"userId\": \"10000\",\n" +  
                "        \"userName\": \"刘德华\",\n" +  
                "        \"userDeteilInfo\": {\n" +  
                "            \"sex\": \"男\"\n" +  
                "        }\n" +  
                "    }\n" +  
                "}\n";  

定义存放被解析的数据的实体类对象

public static class Login{  
        private String code;  
        private String info;  
        private DataBean data;  

        public String getCode() {  
            return code;  
        }  

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

        public String getInfo() {  
            return info;  
        }  

        public void setInfo(String info) {  
            this.info = info;  
        }  

        public DataBean getData() {  
            return data;  
        }  

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

        public static class DataBean {  

            private String userId;  
            private String userName;  
            private UserDeteilInfoBean userDeteilInfo;  

            public String getUserId() {  
                return userId;  
            }  

            public void setUserId(String userId) {  
                this.userId = userId;  
            }  

            public String getUserName() {  
                return userName;  
            }  

            public void setUserName(String userName) {  
                this.userName = userName;  
            }  

            public UserDeteilInfoBean getUserDeteilInfo() {  
                return userDeteilInfo;  
            }  

            public void setUserDeteilInfo(UserDeteilInfoBean userDeteilInfo) {  
                this.userDeteilInfo = userDeteilInfo;  
            }  

            public static class UserDeteilInfoBean {  

                private String sex;  

                public String getSex() {  
                    return sex;  
                }  

                public void setSex(String sex) {  
                    this.sex = sex;  
                }  
            }  
        }  
    }  

数据解析

Login loginTest = new Gson().fromJson(login,Login.class);  
System.out.print(loginTest.getData().getUserName());  

对象中包含集合数据的获取方法:

当数据包含状态码,数据体等信息时,复制数据到实体类中使用AndroidStudio生成实体类为下类代码时,

/** 
     * 数据实体类 
     */  
    public static class music{  
        private AudioinfosBean audioinfos;  

        public AudioinfosBean getAudioinfos() {  
            return audioinfos;  
        }  

        public void setAudioinfos(AudioinfosBean audioinfos) {  
            this.audioinfos = audioinfos;  
        }  

        public static class AudioinfosBean {  
            private List<CatsBean> cats;  

            public List<CatsBean> getCats() {  
                return cats;  
            }  

            public void setCats(List<CatsBean> cats) {  
                this.cats = cats;  
            }  

            public static class CatsBean {  
                /** 
                 * cat_count : 3 
                 * cat_icon_url : http://img.idaddy.cn/f/h/4/xs4ozwyc.jpg 
                 * cat_name : 热门儿歌 
                 * cat_id : 8118 
                 * cat_group_age_scope : -1-6 
                 * cat_parent : 6707 
                 */  

                private String cat_count;  
                private String cat_icon_url;  
                private String cat_name;  
                private int cat_id;  
                private String cat_group_age_scope;  
                private int cat_parent;  

                public String getCat_count() {  
                    return cat_count;  
                }  

                public void setCat_count(String cat_count) {  
                    this.cat_count = cat_count;  
                }  

                public String getCat_icon_url() {  
                    return cat_icon_url;  
                }  

                public void setCat_icon_url(String cat_icon_url) {  
                    this.cat_icon_url = cat_icon_url;  
                }  

                public String getCat_name() {  
                    return cat_name;  
                }  

                public void setCat_name(String cat_name) {  
                    this.cat_name = cat_name;  
                }  

                public int getCat_id() {  
                    return cat_id;  
                }  

                public void setCat_id(int cat_id) {  
                    this.cat_id = cat_id;  
                }  

                public String getCat_group_age_scope() {  
                    return cat_group_age_scope;  
                }  

                public void setCat_group_age_scope(String cat_group_age_scope) {  
                    this.cat_group_age_scope = cat_group_age_scope;  
                }  

                public int getCat_parent() {  
                    return cat_parent;  
                }  

                public void setCat_parent(int cat_parent) {  
                    this.cat_parent = cat_parent;  
                }  
            }  
        }  
    }  

使用类名.方法名,直到找到包含该数据的代码块,取出数据并存到list集合中,遍历输出观察效果

music sc = new Gson().fromJson(msc,music.class);  
List<music.AudioinfosBean.CatsBean> list =sc.getAudioinfos().getCats();  
for (int i = 0; i < list.size(); i++) {  
    System.out.println(list.get(i).cat_name);  
}  

定义模拟的需要解析的数据源

String msc = "{\n" +  
                   "    \"audioinfos\": {\n" +  
                   "        \"cats\": [\n" +  
                   "            {\n" +  
                   "                \"cat_count\": \"3\",\n" +  
                   "                \"cat_icon_url\": \"http://img.idaddy.cn/f/h/4/xs4ozwyc.jpg \n" +  
                   "\n" +  
                   "\",\n" +  
                   "                \"cat_name\": \"热门儿歌\",\n" +  
                   "                \"cat_id\": 8118,\n" +  
                   "                \"cat_group_age_scope\": \"-1-6\",\n" +  
                   "                \"cat_parent\": 6707\n" +  
                   "            },\n" +  
                   "            {\n" +  
                   "                \"cat_count\": \"0\",\n" +  
                   "                \"cat_icon_url\": \"http://img.idaddy.cn/f/h/4/nl9ezckp.jpg \n" +  
                   "\n" +  
                   "\",\n" +  
                   "                \"cat_name\": \"早教儿歌\",\n" +  
                   "                \"cat_id\": 10719,\n" +  
                   "                \"cat_group_age_scope\": \"1-6\",\n" +  
                   "                \"cat_parent\": 6707\n" +  
                   "            },\n" +  
                   "            {\n" +  
                   "                \"cat_count\": \"1\",\n" +  
                   "                \"cat_icon_url\": \"http://img.idaddy.cn/f/h/4/dsws0q0o.jpg \n" +  
                   "\n" +  
                   "\",\n" +  
                   "                \"cat_name\": \"幼儿园童谣\",\n" +  
                   "                \"cat_id\": 11423,\n" +  
                   "                \"cat_group_age_scope\": \"1-6\",\n" +  
                   "                \"cat_parent\": 6707\n" +  
                   "            },\n" +  
                   "            {\n" +  
                   "                \"cat_count\": \"1\",\n" +  
                   "                \"cat_icon_url\": \"http://img.idaddy.cn/f/h/6/f5i1z0n9.jpg \n" +  
                   "\n" +  
                   "\",\n" +  
                   "                \"cat_name\": \"韵律童谣\",\n" +  
                   "                \"cat_id\": 13945,\n" +  
                   "                \"cat_group_age_scope\": \"2-6\",\n" +  
                   "                \"cat_parent\": 6707\n" +  
                   "            },\n" +  
                   "            {\n" +  
                   "                \"cat_count\": \"0\",\n" +  
                   "                \"cat_icon_url\": \"http://img.idaddy.cn/f/h/4/k5xrsszd.jpg \n" +  
                   "\n" +  
                   "\",\n" +  
                   "                \"cat_name\": \"幼小衔接\",\n" +  
                   "                \"cat_id\": 14655,\n" +  
                   "                \"cat_group_age_scope\": \"2-6\",\n" +  
                   "                \"cat_parent\": 6707\n" +  
                   "            }\n" +  
                   "        ]\n" +  
                   "    }\n" +  
                   "}\n";  

含有集合对象的数据解析:

(当Json数据中含有[]中括号时,说明该括号内的数据为集合数据,因此需要使用集合数据的数据解析方法进行解析)
练习1:

服务器返回的Json数据为:

[  
   "111",  
    "222",  
"333"  
]  

看到中括号,说明是一段集合数据

定义模拟的需要解析的数据

String test = "[\n" +  
        "   \"111\",\n" +  
        "    \"222\",\n" +  
        "\"333\"\n" +  
        "]";  

这段数据不是键值对,直接定义一个String类型接收即可

Type type = new TypeToken<List<String>>(){}.getType();//这里的泛型将会决定你的json字符串转化的类型,一般是传实体类的对象  
        //参数1:满足json数组形式的字符串  
        //参数2:Type对象  
        List<String> list = new Gson().fromJson(test,type);  
        System.out.println(list.get(2));  

那么问题来了,如果返回的数据是键值对类型的集合数据呢?

比如

[  
    {  
        "name": "宝宝乐",  
        "cast": "98"  
    },  
    {  
        "name": "宝宝乐1",  
        "cast": "1289"  
    },  
    {  
        "name": "宝宝乐2",  
        "cast": "154"  
    }  
]  

定义模拟的需要解析的数据

String shop = "[\n" +  
                "    {\n" +  
                "        \"name\": \"宝宝乐\",\n" +  
                "        \"cast\": \"98\"\n" +  
                "    },\n" +  
                "    {\n" +  
                "        \"name\": \"宝宝乐1\",\n" +  
                "        \"cast\": \"1289\"\n" +  
                "    },\n" +  
                "    {\n" +  
                "        \"name\": \"宝宝乐2\",\n" +  
                "        \"cast\": \"154\"\n" +  
                "    }\n" +  
                "]";  

定义存放被解析的数据的实体类对象

/** 
    * 被解析的数据的实体类对象 
    */  
   public static class BabyShop{  
       private String name;  
       private String cast;  

       public String getName() {  
           return name;  
       }  

       public void setName(String name) {  
           this.name = name;  
       }  

       public String getCast() {  
           return cast;  
       }  

       public void setCast(String cast) {  
           this.cast = cast;  
       }  
   }  

数据解析

Type type = new TypeToken<List<BabyShop>>(){}.getType();//这里的泛型将会决定你的json字符串转化的类型,一般是传实体类的对象  
    //参数1:满足json数组形式的字符串  
    //参数2:Type对象  
List<BabyShop> list= new Gson().fromJson(shop,type);  

练习2:

定义模拟的需要解析的数据

String integralss = "{ \"userIntegralss\":\"8000\"," +  
        "\"List\":[ {\"integralss\":\"50\"," +  
        "\"name\":\"zhangqi\"},{\"integralss" +  
        "\":\"60\",\"name\":\"lisi\"}]}";  

定义存放被解析的数据的实体类对象

Integrals.class

public static class Integrals{  
        private String userIntegralss;  
        private java.util.List<ListBean> List;  

        public String getUserIntegralss() {  
            return userIntegralss;  
        }  

        public void setUserIntegralss(String userIntegralss) {  
            this.userIntegralss = userIntegralss;  
        }  

        public List<ListBean> getList() {  
            return List;  
        }  

        public void setList(List<ListBean> List) {  
            this.List = List;  
        }  

        public static class ListBean {  

            private String integralss;  
            private String name;  

            public String getIntegralss() {  
                return integralss;  
            }  

            public void setIntegralss(String integralss) {  
                this.integralss = integralss;  
            }  

            public String getName() {  
                return name;  
            }  

            public void setName(String name) {  
                this.name = name;  
            }  
        }  
    }  

数据解析

Integrals jfw = new Gson().fromJson(integralss,Integrals.class);  
List<Integrals.ListBean> list =jfw.getList();  
System.out.println(list.get(0).getIntegralss()); 

将数据转换为Json数据格式

上面讲述了,服务器的Json数据如何解析到本地实体类,那么本地实体类的数据,又要怎么解析成Json数据呢?

定义存放本地数据的实体类

public class Info{  

        private int code;  
        private String info;  
        private int data;  

        public int getData() {  
            return data;  
        }  

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

        public String getInfo() {  
            return info;  
        }  

        public void setInfo(String info) {  
            this.info = info;  
        }  

        public int getCode() {  
            return code;  
        }  

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

定义模拟用户操作数据后,并将数据解析为Json数据的解析方法

public String login(){  
    Info info = new Info();  
    info.setCode(200);  
    info.setData(10000);  
    info.setInfo("注册失败");  
    String result = new Gson().toJson(info);  
    return result;  
}  

调用该解析方法,并将其赋值给result对象保存

String result = login();  

那么这个result对象,便是被解析为Json数据的对象了