0

如何使用 java 对象和 Jackson 递归地创建这个 json 内容?:

{
    "children": [
        {
            "children": [
                {
                    "name": "cluster",
                    "children": [
                        {
                            "name": "AgglomerativeCluster",
                            "size": 3938
                        },
                        {
                            "name": "TestCLuster",
                            "size": 3938
                        }
                    ]
                }
            ],
            "name": "analytics"
        }
    ],
    "name": "flare"
}

到目前为止,这是我的对象结构,一个名为 DendogramVO 的父类和一个名为 Children 的子类,它也有一个子类 List :

import java.util.List;

public class DendogramVO {
    private List<Children> children;
    private String name;

    public List<Children> getChildren() {
        return this.children;
    }

    public void setChildren(List<Children> children) {
        this.children = children;
    }

    public String getName() {
        return this.name;
    }

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

import java.util.List;

public class Children {

    private List<Children> children;
    private String name;

    public List<Children> getChildren() {
        return children;
    }

    public void setChildren(List<Children> children) {
        this.children = children;
    }

    public String getName() {
        return name;
    }

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

}
4

1 回答 1

2

请注意,您的 JSON 包含未知属性。您需要配置在ObjectMapper遇到它们时不会失败(或将它们添加到您的课程中)

String s="{ \"children\": [ { \"children\": [ { \"name\": \"cluster\", \"children\": [ { \"name\": \"AgglomerativeCluster\", \"size\": 3938 }, { \"name\": \"TestCLuster\", \"size\": 3938 } ] } ], \"name\": \"analytics\" } ], \"name\": \"flare\"}";
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Children children = mapper.readValue(s, Children.class);

System.out.println(children.getChildren());

用简单的Children#toString()印花

[[children = [[children = [[children = null, name = AgglomerativeCluster], [children = null, name = TestCLuster]], name = cluster]], name = analytics]]
于 2013-10-15T20:28:20.143 回答