Una biblioteca para convertir POJO al formato Cytoscape.js JSON

Estoy trabajando en un proyecto que requiere la creación de un servlet en Java para servir JSON al cliente para que se muestre en Cytoscape.js.

El formato JSON se ve así:

var cy = cytoscape({
  /* ... */

  container: document.getElementById('cy'),

  elements: {
    nodes: [
      { data: { id: 'foo' } }, // NB no group specified

      { data: { id: 'bar' } },

      {
        data: { weight: 100 }, // elided id => autogenerated id 
        group: 'nodes',
        position: {
          x: 100,
          y: 100
        },
        classes: 'className1 className2',
        selected: true,
        selectable: true,
        locked: true,
        grabbable: true
      }
    ],

    edges: [
      { data: { id: 'baz', source: 'foo', target: 'bar' } } // NB no group specified
    ]
  }

  /* ... */
});

Actualmente, estoy generando mi JSON con métodos que se ven así:

private JSONObject genJsonNode(SimpleNode node) throws JSONException
{
    JSONObject jNode = new JSONObject();
    JSONObject data = new JSONObject();
    JSONObject position = new JSONObject();

    data.put("id",  node.getId());
    position.put("x", node.getX());
    position.put("y", node.getY());

    jNode.put("data", data);
    jNode.put("position", position);



    return jNode;
}

Me pregunto si hay una biblioteca que ya está haciendo esto por mí.

Respuestas (1)

Con Gson puede convertir POJO a JSON fácilmente, por ejemplo:

import com.google.gson.*;

class ElementData {

    String id;
    Integer weight;
    // ...
}

class Node {

    final ElementData data = new ElementData();
    String group;
    String classes;
    boolean selected;
    // ...
}

class Edge {

    final ElementData data = new ElementData();
    // ...
}

class GraphElements {

    final List<Node> nodes = new ArrayList<>();
    final List<Edge> edges = new ArrayList<>();

}

class Graph {

    final GraphElements elements = new GraphElements();
}

void printSampleGraph() {
    Graph g = new Graph();
    Node n1 = new Node();
    n1.data.id = "foo";
    g.elements.nodes.add(n1);
    Node n2 = new Node();
    n2.data.id = "bar";
    g.elements.nodes.add(n2);
    Edge e = new Edge();
    e.data.id = "baz";
    g.elements.edges.add(e);    

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = gson.toJson(g);
    System.out.println(json);

}

La llamada printSampleGraphimprimirá el siguiente resultado:

{
  "elements": {
    "nodes": [
      {
        "data": {
          "id": "foo"
        },
        "selected": false
      },
      {
        "data": {
          "id": "bar"
        },
        "selected": false
      }
    ],
    "edges": [
      {
        "data": {
          "id": "baz"
        }
      }
    ]
  }
}