Gson解析json数据的案例一

转自:http://blog.csdn.net/l331258747/article/details/51547338;

Android利用Gson解析嵌套多层的Json

首先先讲一个比较简单点的例子(最简单的我就不讲啦,网上很多),帮助新手理解Gson的使用方法:
比如我们要解析一个下面这种的Json:
String json = {"a":"100","b":[{"b1":"b_value1","b2":"b_value2"},{"b1":"b_value1","b2":"b_value2"}],"c":{"c1":"c_value1","c2":"c_value2"}}

首先我们需要定义一个序列化的Bean,这里采用内部类的形式,看起来会比较清晰一些:

一个".java"源文件中是否可以包括多个类(不是内部类)?有什么限制?
可以有多个类,但只能有一个 public 的类,并且 public 的类名必须与文件名相一致

public class jsonBean {

    private String a;
    private List<bb> b; 
    public C c;
    
    public class bb{
        private  String b1;
        private  String b2;
        public String getB1() {
            return b1;
        }
        public void setB1(String b1) {
            this.b1 = b1;
        }
        public String getB2() {
            return b2;
        }
        public void setB2(String b2) {
            this.b2 = b2;
        }
    }
    
    public class  C{
        private String c1;
        private String c2;
        public String getC1() {
            return c1;
        }
        public void setC1(String c1) {
            this.c1 = c1;
        }
        public String getC2() {
            return c2;
        }
        public void setC2(String c2) {
            this.c2 = c2;
        }
    }

    public String getA() {
        return a;
    }

    public void setA(String a) {
        this.a = a;
    }

    public List<bb> getB() {
        return b;
    }

    public void setB(List<bb> b) {
        this.b = b;
    }

    public C getC() {
        return c;
    }

    public void setC(C c) {
        this.c = c;
    }
}
public static void main(String[] args) {
         String jsonstr ="{"a":"100","b": [{ "b1": "b_value1","b2": "b_value2"},{"b1": "b_value1","b2": "b_value2"}] ,"
                 + ""c": {"c1": "c_value1","c2": "c_value2"}}";
         
         Gson gson = new Gson();
         
         jsonBean jsbean=gson.fromJson(jsonstr, jsonBean.class);
         //java.lang.reflect.Type type = new TypeToken<jsonBean>() {}.getType();//Gson的第二种构造比较麻烦
         //jsonBean jsbean = gson.fromJson(json, type);
          
         System.out.println(jsbean.getA());
         System.out.println(jsbean.getB().get(0).getB1());
         System.out.println(jsbean.getB().get(0).getB2());
         System.out.println();
         System.out.println(jsbean.getB().get(1).getB2());
         
         System.out.println(jsbean.getC().getC1());
         System.out.println(jsbean.getC().getC2());
    }    

       很多时候大家都是不知道这个Bean是该怎么定义,这里面需要注意几点:
             1、类里面的属性名必须跟Json字段里面的Key是一模一样的;
             2、内部嵌套的用[]括起来的部分是一个List,所以定义为 public List<B> b,而只用{}嵌套的就定义为 public C c,

       如果需要解析的Json嵌套了很多层,同样可以可以定义一个嵌套很多层内部类的Bean,需要细心的对照Json字段来定义哦。

原文地址:https://www.cnblogs.com/xh_Blog/p/6633234.html