json-lib解析复杂对象

public class Father {
    Son son;
    List<Cat> cats;

    public List<Cat> getCats() {
        return cats;
    }

    public void setCats(List<Cat> cats) {
        this.cats = cats;
    }

    public Son getSon() {
        return son;
    }

    public void setSon(Son son) {
        this.son = son;
    }
}


public class Son {
    String name;
    Cat cat;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }
}


public class Cat {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


public class TestJson {
    public static void main(String[] args) {
        String json = "{name:'father', 'son':{'name':'son', 'cat':{'name':'catSon'}}, 'cats':[{'name':'catOne'}, {'name':'catTwo'}]}";
        Map classMap = new HashMap();
//        classMap.put("son", Son.class);
        classMap.put("cats", Cat.class);
//        classMap.put("cat", Cat.class);
        JSONObject jsonObject = JSONObject.fromObject(json);
        Father father = (Father) JSONObject.toBean(jsonObject, Father.class, classMap);
        System.out.println();
    }
}

除了List需要用到classMap外.对象内的子对象都自动装配好了.生成如下father对象

father

  son
    name = son
    cat
       name = catSon

  cats
    catOne
    catTwo
 

你可能感兴趣的:(json)