Skip to main content

Developing with XCC

Processing JSON Query Results

If you run an ad hoc query that returns JSON (or a JavaScript object or array), you can use Jackson to traverse and manipulate the data in your Java application.

For example, the following code snippet evaluates an ad hoc Server-Side JavaScript query that retrieves a JSON document from the database, and then accesses the value in the document’s “num” property as an integer:

Session session = cs.newSession();
AdhocQuery request = 
    session.newAdhocQuery("cts.doc('/xcc/fromString.json')");
RequestOptions options = new RequestOptions();
options.setQueryLanguage("javascript");
request.setOptions(options);
ResultSequence rs = session.submitRequest(request);
while (rs.hasNext()) {
    XdmItem item = rs.next().getItem();
    if (item instanceof JsonItem) {
        JsonItem jsonItem = (JsonItem) item;
        JsonNode node = jsonItem.asJsonNode();
        // process the value...
    }
}

You can use JsonItem.asJsonNode to convert a JSON result item into a Jackson JsonNode (com.fasterxml.jackson.databind.JsonNode). For example:

JsonItem jsonItem = (JsonItem) item;
JsonNode node = jsonItem.asJsonNode();

You can also use the Jackson interfaces to manipulate native JavaScript objects and arrays returned by ad hoc Server-Side JavaScript queries. That is, the above conversion to a JsonNode works whether the item is a JSON node or an atomic JS_OBJECT result.

Then you can use any of the Jackson interfaces to manipulate the contents. For example, the following code snippet accesses the value of the “num” JSON property as an integer:

node.get("num").asInt()

To learn more about Jackson, see http://github.com/FasterXML/jackson-docs