Gson的使用

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值