JSON.parseObject将json转换为对象,包含三层对象转换和嵌
套转换
public class JSONTest {
public static void main(String[] args){
String json1="{\n" +
" \"name\": \"skynet\",\n" +
" \"info\": {\n" +
" \"s2\": 18,\n" +
" \"newList\": [\n" +
" \"C++\",\n" +
json转换对象" \"JAVA\",\n" +
" \"C#\"\n" +
" ],\n" +
" \"sub\": {\n" +
" \"s3\": true,\n" +
" \"sl\": 12.2222,\n" +
" \"map\": {\n" +
" \"student1\": {\n" +
" \"name\": \"mike\",\n" +
" \"info\": {\n" +
" \"s2\": 14,\n" +
" \"newList\": [\n" +
" \"int\",\n" +
" \"float\",\n" +
" \"char\"\n" +
" ],\n" +
" \"sub\": \"\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
Students students=JSON.parseObject(json1,Students.class);
System.out.String());
}
}
class Students{
private String name;
private Info info; //第⼆层对象
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Info getInfo() {
return info;
}
public void setInfo(Info info) {
this.info = info;
this.info = info;
}
@Override
public String toString(){
return "name: "+name+" "+ "info: "+String();
}
}
class Info {
private int s2;
private List<String> newList;
private Sub sub; //第三层对象
public int getS2() {
return s2;
}
public void setS2(int s2) {
this.s2 = s2;
}
public List<String> getNewList() {
return newList;
}
public void setNewList(List<String> newList) {
}
public Sub getSub() {
return sub;
}
public void setSub(Sub sub) {
this.sub = sub;
}
@Override
public String toString(){
return "s2: "+s2+" "+"sub: "+sub+" "+"list: "+newList; }
}
//继承SL对象
class Sub extends SL{
private boolean s3;
private Map<String,Students> map; //循环嵌套对象
public boolean isS3() {
return s3;
}
public void setS3(boolean s3) {
this.s3 = s3;
}
public Map<String, Students> getMap() {
return map;
}
public void setMap(Map<String, Students> map) {
this.map = map;
}
}
@Override
public String toString(){
return "s3: "+s3+" "+"map: "+map+" "+"sl: "+String();
}
}
class SL{
private double sl;
public double getSl() {
return sl;
}
public void setSl(double sl) {
this.sl = sl;
}
@Override
public String toString(){
return "sl: "+sl;
}
}
运⾏结果:
name: skynet info: s2: 18 sub: s3: true map: {student1=name: mike info: s2: 14 sub: null list: [int, float, char]} sl: sl: 12.2222 list: [C++, JAVA, C#]
使⽤JSON.parseObject⽅法将json转化为对象时,对象之间可以多层嵌套,也可以循环嵌套。对象也可以继承其他对象
注意:对象的setter和getter⽅法要齐全,少⼀个则对应的内容会提取不到。
记录于此
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论