Gson的使用

来源:互联网 发布:毕业生自我鉴定知乎 编辑:程序博客网 时间:2024/06/10 05:51

1、GitHub地址:

https://github.com/google/gson

导入依赖:

compile 'com.google.code.gson:gson:2.8.0'

2、
JavaBean转换成Json:

Gson gson = new Gson();  Student student = new Student();  student.setName("xingming");  student.setAge(26);  String jsonStr = gson.toJson(student); 

List或者Map转换成Json:
List转换结果为[];
Map转换结果为{}对应的键值对

//使用Gson把集合里的数据, 变成JSON字符串Gson gson = new Gson();String json = gson.toJson(list);

3、
Json字符串转JavaBean

Student student = gson.fromJson(jsonStr, Student.class);  

Json字符串转List

// 把文件里的JSON字符串变成对象 (ArrayList<Info>)Gson gson = new Gson();Type type = new TypeToken<ArrayList<Info>>(){}.getType();ArrayList<Info> list = gson.fromJson( new FileReader(file), type);

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

{"a":"100","b":[{"b1":"b_value1","b2":"b_value2"}, {"b1":"b_value1","b2":"b_value2"}],"c": {"c1":"c_value1","c2":"c_value2"}}

定义类:

public class JsonBean {      public String a;      public List<B> b;      public C c;      public static class B {         public String b1;         public String b2;     }     public static class C {         public String c1;         public String c2;    } }

5、注释
1、

@SerializedName( "address")public String mAddress ;

代表意义就是服务端实际字段为address,而我们使用的字段为mAddress

0 0