gson @SerializedName 用法

假设我们想用gson把如下的json字符串转成一个Student对象,正常情况下是无法成功解析的,因为json的键名和Java类的变量名不一致,这种情况在开发中很常见,后台服务器返回的json字段经常不符合java的驼峰命名规范,有的带下划线,有的首字母没有小写,如果我们不想改变原有的Java类变量名又想成功解析,可以借助@SerializedName

同理,在Java对象转json字符串时如果像转成和变量名不同的json key,也可以用@SerializedName

1
{"student_age":28,"student_name":"野猿新一"}

Click and drag to move

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Student {
@SerializedName("student_name")
public String name;
@SerializedName("student_age")
public int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}

@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

Click and drag to move

json转Java对象

1
2
3
4
5
6
public void toObject() {
// {"student_age":28,"student_name":"野猿新一"}
String json = "{\"student_age\":28,\"student_name\":\"野猿新一\"}";
Student student = new Gson().fromJson(json, Student.class);
Log.d("gson", student.toString()); // 输出结果为 Student{name='野猿新一', age=28}
}

Click and drag to move

java对象转json

1
2
3
4
5
public void printJson2() {
Student student = new Student("野猿新一", 28);
String json = new Gson().toJson(student);
Log.d("json", json); // 输出结果为{"student_age":28,"student_name":"野猿新一"}
}

Click and drag to move