【发布时间】:2018-03-07 06:39:18
【问题描述】:
我正在尝试从 Java 创建一个 JSON 对象,以使用 D3 呈现分层图。
JSON 的结构:
{
"name": "Homepage",
"parent": "null",
"children": [
{
"name": "Import",
"parent": "Homepage",
"children": [
{
"name": "Ready to be Imported",
"size": 1000,
"parent": "Import"
},
{
"name": "Ack with parsing error",
"size": 9,
"parent": "Import Section"
},
]
},
]
}
JSON 对象中存在父子关系,我使用下面的代码来创建 JSON 对象 -
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import com.google.gson.Gson;
public class Hirarchy {
public static class Entry {
private String name;
public Entry(String name) {
this.name = name;
}
private List<Entry> children;
public void add(Entry node) {
if (children == null)
children = new ArrayList<Entry>();
children.add(node);
}
public static void main(String[] args) throws JSONException {
List<String> listofParent = new ArrayList<String>();
listofParent.add("Import");
List<String> importChild = new ArrayList<String>();
importChild.add("Ready to be Imported");
importChild.add("Ack with parsing error");
Entry mainRoot=null;
for (int i = 0; i < listofParent.size(); i++) {
Entry root = new Entry(listofParent.get(i));
mainRoot= aMethod2form(root, importChild);
Entry e=new Entry("Homepage");
e.add(mainRoot);
Gson g=new Gson();
System.out.println(g.toJson(e));
}
}
private static Entry aMethod2form(Entry root, List<String> listofChild) throws JSONException {
for(int i=0;i<listofChild.size();i++){
root.add(new Entry(listofChild.get(i)));
}
return root;
}
}
}
使用这个java代码,我可以创建父子关系,但是如何为每个孩子添加大小和父属性?
【问题讨论】:
-
你的代码看起来有点奇怪......你在嵌套的静态类
Entry中真的有main()吗?尽管这可能有效,但它完全出乎意料,应该在Hierarchy本身上声明,您不同意吗?aMethod2form()也一样。 -
altocumulus,好的,我会考虑你的建议,但是他们有什么方法可以为每个孩子增加尺寸和父母吗?
标签: javascript java json d3.js hierarchy