Gson 是一个强大的用于json 序列化和反序列化的库,注解也是其比较重要的一部分,今天我们就来学习下注解SerializedName。
1. SerializedName
@SerializedName("len")
int length;
SerializedName 序列化名称,在序列化时会将length 替换成len 字符串,同样在反序序列化时将json 字符传中的key 为len 的值设置到length变量上。
实例:
实体类
public class TestMode {
@Expose(deserialize = true)
private int age;
@Expose(serialize = false, deserialize = true)
String name;
@Expose(deserialize = true)
@SerializedName("len")
int length;
public TestMode() {
if (false) {
}
}
public TestMode(int age, String name, int length) {
this.age = age;
this.name = name;
this.length = length;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "TestMode{" +
"age=" + age +
", name='" + name + '\'' +
", length=" + length +
'}';
}
}
测试代码:
Gson gson = new Gson();
TestMode testMode = new TestMode(30, "明", 170);
System.out.println("序列化:"+gson.toJson(testMode));
String json="{\"age\":30,\"name\":\"明\",\"len\":170}";
TestMode jsTestMode=gson.fromJson(json,TestMode.class);
System.out.println("反序列化:"+jsTestMode.toString());
结果:
序列化:{"age":30,"name":"明","len":170}
反序列化:TestMode{age=30, name='明', length=170}
多字段匹配:
@SerializedName(value = "len",alternate = {"height","width"})
int length;
value 是默认字段,alternate 配置的字段只有反序列化才有效,len,height,width,都可以将值转化为length 的值,如果json中同时出现多个配置字段,将以最后一个为准。
String json="{\"age\":30,\"name\":\"明\",\"len\":20,\"width\":80,\"height\":70}";
TestMode jsTestMode=gson.fromJson(json,TestMode.class);
System.out.println("反序列化:"+jsTestMode.toString());
结果:
反序列化:TestMode{age=30, name='明', length=70}