json
- 数组类型的json对象:[{“name”:”老彭”,”sex”:”男”},{“name”:”小彭”,”sex”:”男”}]
String s2 = "[{\"name\":\"老彭\",\"sex\":\"男\"},{\"name\":\"小彭\",\"sex\":\"男\"}]";
List<People> list = jsonToList(s2, People.class);
People的类
private String name;
private String sex;
private String color;
- 普通类型的json对象:{“name”:”老彭”,”sex”:”男”}
String s2 = "{\"name\":\"老彭\",\"sex\":\"男\"}";
People people = jsonToPojo(s2, People.class);
People的类
private String name;
private String sex;
private String color;
- 普通json对象嵌套json数组:{\”list\”:[{\”name\”:\”小彭\”,\”sex\”:\”男\”},{\”name\”:\”大彭\”,\”sex\”:\”男\”}]}
String json = "{\"list\":[{\"name\":\"小彭\",\"sex\":\"男\"},{\"name\":\"大彭\",\"sex\":\"男\"}]}";
Man man = jsonToPojo(json, Man.class);
Man对象
private List<People> list;
People对象
private String name;
private String sex;
private String color;
- 普通JSON对象嵌套Integer数组{\”arr\”:[\”1\”,\”2\”,\”3\”]}:
String json = "{\"arr\":[\"1\",\"2\",\"3\"],\"name\":\"小彭\"}";
People pojo = jsonToPojo(json,People.class);
People类
private String name;
private String sex;
private String color;
private List<Integer> arr;
- 总结
- json(键值对)中的键要在pojo中要有set方法后的名称对应。(对应的不是属性)
String json ="{\"name2\":\"小彭\"}";
People pojo = jsonToPojo(json,People.class);
People类
private String name;
public String getName2() {
return name;
}
public void setName2(String name) {
this.name = name;
}
- pojo中属性可以在json中没有对应,属性没有对应,获得到的是null。
String s2 = "{\"name2\":\"老彭\",\"sex\":\"男\"}";
People people = jsonToPojo(s2,People.class);
System.out.println(pojo.getColor()+pojo.getName2()+pojo.getSex());
People的类
private String name;
private String sex;
private String color;
public String getName2() {
return name;
}
public void setName2(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
- 一个json对象对应的是一个pojo。一个数组类型json对象对应的着一个list。一个json对象中嵌套数组类型json对象对应着一个pojo中有个list集合。一个普通数组对应着list,list
String json = "{\"arr\":[\"1\",\"2\",\"3\"],\"name\":\"小彭\"}";
People pojo = jsonToPojo(json,People.class);
People类
private String name;
private String sex;
private String color;
private List<Integer> arr;