gpt4 book ai didi

javascript - 为 D3 层次图创建 JSON 对象

转载 作者:行者123 更新时间:2023-11-30 20:42:09 25 4
gpt4 key购买 nike

我正在尝试从 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);
}
}

关于javascript - 为 D3 层次图创建 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49145676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com