将json字符串转换为自定义对象
将json转自定义对象或者List
String json = "{\"name\":cece}";
Gson gson = new Gson();
Person person1 = gson.fromJson(json,Person.class);
System.out.println("pppp"+person1.toString());
json = "[{\"name\":cece},{\"name\":ddddd}]";
Type listType = new TypeToken<List<Person>>() {
}.getType();
List<Person> data = gson.fromJson(json,listType);
for (int i = 0;i<data.size();i++){
System.out.println("data "+i+data.get(i).toString());
}
打印的数据
装换后的数据:name:cece,age:15,desc:这是一个学生
装换后的数据0:name:cece,age:15,desc:这是一个学生
装换后的数据1:name:ddddd,age:15,desc:这是一个学生
创建对象Person
public class Person {
private String name = "张三";
private int age = 15;
private String desc ="这是一个学生";
public Person() {
}
public Person(String name, int age, String desc) {
this.name = name;
this.age = age;
this.desc = desc;
}
private String getName() {
return name;
}
private void setName(String name) {
this.name = name;
}
private int getAge() {
return age;
}
private void setAge(int age) {
this.age = age;
}
private String getDesc() {
return desc;
}
private void setDesc(String desc) {
this.desc = desc;
}
@NonNull
@Override
public String toString() {
return "name:"+getName()+",age:"+getAge()+",desc:"+getDesc();
}
}