为D3分层图创建JSON对象

时间:2018-03-07 06:39:19

标签: javascript java json d3.js hierarchy

我正在尝试使用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代码,我能够创建父子关系,但是如何为每个子项添加大小和父属性?

1 个答案:

答案 0 :(得分:1)

您的入门课程应如下所示:

public static class Entry {
    private String name;

    public Entry(String name) {
        this.name = name;
    }

    private List<Entry> children;
    private Entry parent; // This will contain the referenece of parent object.

    public void add(Entry node) {
        if (children == null)
            children = new ArrayList<Entry>();
        node.parent = this; // This will make the current object as parent of child object.
        children.add(node);
    }
}