ノードを使用してツリー構造を作成し、XStreamを使用して構造をシリアル化します。以下の例で、これがお役に立てば幸いです。
ノード構造への変換
public static Node createNodes(Map<List<String>, Integer> map) {
Map<String, Node> namemap = new HashMap<String, Node>();
Node root = new Node();
Node current;
for (Entry<List<String>, Integer> path : map.entrySet()) {
current = root;
for (String nodename : path.getKey()) {
Node p;
if (!namemap.containsKey(nodename)){
p = new Node(nodename, path.getValue());
namemap.put(nodename, p);
}else {
p = namemap.get(nodename);
p.addCost(path.getValue());
}
current.addChild(p);
current = p;
}
}
return root;
}
シリアル化
public static String toXML(Node n) {
XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
xstream.alias("node", Node.class);
return xstream.toXML(n);
}
ノードオブジェクト
public class Node {
private String name;
private int count;
private List<Node> children;
public Node() {
this(null, 0);
}
public Node(String name, int count) {
this.name = name;
this.count = count;
this.children = new ArrayList<Node>();
}
public void addChild(Node n) {
for (Node nn : children) {
if (nn.name.equals(n.name)) {
return;
}
}
this.children.add(n);
}
public void addCost(int i) {
this.count += i;
}
}
JSON出力
{"node": {
"count": 0,
"children": [
{
"name": "c1",
"count": 5,
"children": [
{
"name": "c2",
"count": 5,
"children": [
{
"name": "c3",
"count": 5,
"children": [
{
"name": "c4",
"count": 5,
"children": [
]
}
]
}
]
}
]
},
{
"name": "b1",
"count": 10,
"children": [
{
"name": "b2",
"count": 6,
"children": [
{
"name": "b3",
"count": 3,
"children": [
]
}
]
}
]
},
{
"name": "a1",
"count": 6,
"children": [
{
"name": "a2",
"count": 6,
"children": [
{
"name": "a3",
"count": 4,
"children": [
]
}
]
}
]
}
]
}}