簡體   English   中英

為 D3 分層圖創建 JSON 對象

[英]Creating JSON Object for D3 Hierarchical Graph

我正在嘗試從 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 代碼,我可以創建父子關系,但是如何為每個子項添加大小和父屬性?

您的入口類應如下所示:

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