美文网首页安卓开发
GSON解析返回的json

GSON解析返回的json

作者: 水固态中 | 来源:发表于2018-01-27 23:28 被阅读0次

    1.依赖

    //Gson
    compile 'com.google.code.gson:gson:2.3.1'
    

    2.创建一个bean类与json对应
    json

    {
      "code": 1,
      "msg": "OK",
       data": [
        {
          "name": "zhangsan",
          "age": "10",
          "phone": "11111",
          "email": "11111@11.com"
        },
        {
          "name": "lisi",
          "age": "20",
          "phone": "22222",
          "email": "22222@22.com"
        },
        ...
      ]
    }
    

    对应类

    public class NewsResultBean
    {  
        private int code;
        private String msg;
        private List<NewsBean> data;
        
        public class NewsBean 
        {
            private int id;//文章id
            private int sid;//频道
            private int userid;
            private int updatetime;
            private int status;
            private int hits;
            private int createtime;
            private String username;
            private String title;
            private String thumb;
            private String content;
            private String description;
             ...
           }
        ...
    }
    
    
    

    3.返回json处理

    //GSON直接解析成对象   
    
    NewsResultBean newsResultBean = new Gson().fromJson(resultjson,NewsResultBean.class);
    
    //对象中拿到集合           
    
    final List<NewsResultBean.NewsBean> newsBeanList = newsResultBean.getNewsBeanList();
    
    //展示到UI中    
    
    mNewsListView.setAdapter(new NewsAdapter(ActivityNewsList.this, newsBeanList));
                        
    

    相关文章

      网友评论

        本文标题:GSON解析返回的json

        本文链接:https://www.haomeiwen.com/subject/fugoaxtx.html