1

I have a graph created using JgraphT where I have some data associated with every Node. I need to create a JSON representation of this graph.

For instance I have 3 vertexes : A->B and A->C where A is a parent of B and C. Every node has some data associated with it. A ( dataPoint1 , ... , dataPointN ).

I want to create a JSON object that should look like that :

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

                          }
                         ]

}

I can probably use BreadthIterator and generate a JSON string and then convert it to JSON object, but I am wondering if there is an existing API that allows me to do it. I am pretty sure someone already implemented something like that.

vs777
  • 564
  • 2
  • 11
  • 24

1 Answers1

2

You can simply use the JSON exporter included in the jgrapht-nio package. Various examples on how to use this exporter are included in the JSONExporterTest unit test class.

Let's assume your vertex class looks something like this:

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

Then your JSON exporter could look like:

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

For a more elaborate example, refer to the aforementioned JSONExporterTest class.

Joris Kinable
  • 2,232
  • 18
  • 29