Json
依赖
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
序列化
Student student1 =new Student("Jack",20);
Gson gson=new Gson();
String jsonStudent1=gson.toJson(student1);
Gson gson=new Gson();
Student student1=new Student("Mike",20,new Score(90,80,70));
Student student2=new Student("Lisa",21,new Score(91,81,71));
Student[] students={student1,student2};
String jsonStudents=gson.toJson(students);
Gson gson=new Gson();
Student student1=new Student("Mike",20,new Score(90,80,70));
Student student2=new Student("Lisa",21,new Score(91,81,71));
List<Student> studentList=new ArrayList<>();
studentList.add(student1);
studentList.add(student2);
String jsonStudents=gson.toJson(studentList);
反序列化
Gson gson=new Gson();
String jsonStudent1="{\"age\":20,\"name\":\"Jack\"}";
Student student1=gson.fromJson(jsonStudent1,Student.class);
Gson gson=new Gson();
String jsonStudents="[{\"age\":20,\"name\":\"Mike\",\"score\":{\"Chinese\":70,\"English\":80,\"math\":90}},{\"age\":21,\"name\":\"Lisa\",\"score\":{\"Chinese\":71,\"English\":81,\"math\":91}}]";
Student[] students=gson.fromJson(jsonStudents,Student[].class);
Gson gson=new Gson();
Score(91,81,71));
List<Student> studentList=new ArrayList<>();
String jsonStudents="[\n" +
" {\n" +
" \"age\": 20,\n" +
" \"name\": \"Mike\",\n" +
" \"score\": {\n" +
" \"Chinese\": 70,\n" +
" \"English\": 80,\n" +
" \"math\": 90\n" +
" }\n" +
" },\n" +
" {\n" +
" \"age\": 21,\n" +
" \"name\": \"Lisa\",\n" +
" \"score\": {\n" +
" \"Chinese\": 71,\n" +
" \"English\": 81,\n" +
" \"math\": 91\n" +
" }\n" +
" }\n" +
"]";
Type typeStudents=new TypeToken<List<Student>>(){}.getType();
studentList=gson.fromJson(jsonStudents,typeStudents);
字段重命名
在类中添加@SerializedName(“student_name”):
public class Student {
@SerializedName("student_name")
private String name;
private int age;
private Score score;
}
此时序列化结果name更名为student_name:
{
"age": 20,
"student_name": "Rose",
"score": {
"Chinese": 33,
"English": 22,
"math": 11
}
}
序列化中忽略某字段
使用transient关键字。