使用Gson解析含有动态key的Json
2019-12-25 本文已影响0人
土豆吞噬者
使用Gson解析Json时,有时候会遇到key不是固定的情况,这个时候可以把它当做是一个Map。
{
"students":{
"101":{
"name":"xiao hong",
"age":10
},
"102":{
"name":"xiao ming",
"age":12
},
"103":{
"name":"xiao qiang",
"age":14
}
}
}
public class School {
private Map<String,Student> students;
public Map<String,Student> getStudents() {
return students;
}
public void setStudents(Map<String,Student> students) {
this.students = students;
}
public static class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
public School(Map<String, Student> students) {
this.students = students;
}
}
public class ExampleUnitTest {
@Test
public void testDeserializeSchool() {
String data="{\n" +
" \"students\": {\n" +
" \"101\": {\n" +
" \"name\": \"xiao hong\",\n" +
" \"age\": 10\n" +
" },\n" +
" \"102\": {\n" +
" \"name\": \"xiao ming\",\n" +
" \"age\": 12\n" +
" },\n" +
" \"103\": {\n" +
" \"name\": \"xiao qiang\",\n" +
" \"age\": 14\n" +
" }\n" +
" }\n" +
"}";
Gson gson = new Gson();
School school = gson.fromJson(data, School.class);
Map<String,School.Student> students=school.getStudents();
for (String key:students.keySet()){
School.Student student=students.get(key);
System.out.println("key:"+key+",name:"+student.getName()+",age:"+student.getAge());
}
//key:101,name:xiao hong,age:10
//key:102,name:xiao ming,age:12
//key:103,name:xiao qiang,age:14
}
@Test
public void testSerializeSchool() {
Gson gson = new Gson();
Map<String,School.Student> students=new HashMap<>();
students.put("104",new School.Student("xiong da",20));
students.put("105",new School.Student("xiong er",19));
students.put("106",new School.Student("xiong san",18));
String data=gson.toJson(new School(students));
System.out.println(data);
//{"students":{"104":{"name":"xiong da","age":20},"105":{"name":"xiong er","age":19},"106":{"name":"xiong san","age":18}}}
}
}