简体   繁体   English

为 D3 分层图创建 JSON 对象

[英]Creating JSON Object for D3 Hierarchical Graph

I'm trying to create a JSON Object from Java for rendering a hierarchical graph using D3.我正在尝试从 Java 创建一个 JSON 对象,用于使用 D3 呈现分层图。

The structure of the JSON: 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"
        },

      ]
    },

  ]
}

There is a parent child relationship in the JSON object, and I'm using the below code to create the JSON object - 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;
    }
}
}

with this java code, i'm able to create the parent child relationship, but how to add size and parent attributes for each children?使用此 java 代码,我可以创建父子关系,但是如何为每个子项添加大小和父属性?

Your entry class should look like this:您的入口类应如下所示:

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM