【问题标题】:Create a JSON object from JgraphT从 JgraphT 创建一个 JSON 对象
【发布时间】:2021-12-18 20:19:26
【问题描述】:

我有一个使用 JgraphT 创建的图表,其中我有一些与每个节点关联的数据。我需要为此图创建一个 JSON 表示。

例如,我有 3 个顶点:A->B 和 A->C,其中 A 是 B 和 C 的父节点。每个节点都有一些与之关联的数据。 A ( dataPoint1 , ... , dataPointN )。

我想创建一个看起来像这样的 JSON 对象:

element {
          "nodeId"     : "A",  
          "dataPoint1" : "value1",
           .....
          "dataPoint2" : "value2",
          "children"   : [ 
                          { 
                           "nodeId" : "B",
                           "dataPoint1" : "value211",
                             .....
                           "dataPoint2" : "value221" 
                          },
                          {
                            "nodeId" : "C",
                           "dataPoint1" : "value221",
                             .....
                           "dataPoint2" : "value222"  

                          }
                         ]

}

我可能可以使用 BreadthIterator 并生成一个 JSON 字符串,然后将其转换为 JSON 对象,但我想知道是否存在允许我这样做的现有 API。我很确定有人已经实现了类似的东西。

【问题讨论】:

    标签: java json spring-boot jgrapht


    【解决方案1】:

    您可以简单地使用jgrapht-nio 包中包含的JSON exporter。 JSONExporterTest 单元测试类中包含有关如何使用此导出器的各种示例。

    假设您的顶点类看起来像这样:

    public class MyVertex{
        public final String ID;
        public final int dataPoint1;
        public final double dataPoint2;
        ...
    }
    

    那么您的 JSON 导出器可能如下所示:

    Graph<MyVertex,DefaultEdge> graph = .... //Define your graph with your custom vertex type
    
    //Define a vertex attribute provider
    Function<MyVertex, Map<String, Attribute>> vertexAttributeProvider = v -> {
        Map<String, Attribute> map = new LinkedHashMap<>();
        map.put("dataPoint1", DefaultAttribute.createAttribute(v.dataPoint1));
        map.put("dataPoint2", DefaultAttribute.createAttribute(v.dataPoint1));
        return map;
    };
    
    
    //Create a JSON graph exporter with a vertexIdProvider which tells
    //the exporter how to name each vertex
    JSONExporter<MyVertex, DefaultEdge> exporter = new JSONExporter<>(v -> v.ID);
    exporter.setVertexAttributeProvider(vertexAttributeProvider);
    
    //Export the graph
    exporter.exportGraph(graph,new File("./graph.json"));
    

    有关更详细的示例,请参阅前面提到的JSONExporterTest 类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-18
      • 2021-12-24
      • 2018-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-04
      • 2018-12-29
      相关资源
      最近更新 更多