3

I'm working on a project that requires creating a servlet in Java to serve up JSON to client to display in Cytoscape.js.

The JSON format looks like this:

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
    ]
  }

  /* ... */
});

Currently, I'm generating my JSON with methods that look like this:

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;
}

I'm wondering if there's a library that's already doing this for me.

1

With Gson you can convert POJOs to JSON easily, e.g.:

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

}

Calling printSampleGraph will print the following output:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.