Skip to main content

Developing with XCC

Inserting JSON Documents

You can insert JSON data into the database the same way you insert other data. If the document URI extension is mapped to the JSON document format in the MarkLogic Server MIME type mappings, then a JSON document is automatically created.

For example, the following code snippet reads JSON data from a file and inserts it into the database as a JSON document.

ContentSource cs = ContentSourceFactory.newContentSource(SERVER_URI);
Session session = cs.newSession();
File inputFile = new File("data.json");
String uri = "/xcc/fromFile.json";
Content content = ContentFactory.newContent(uri, inputFile, null);
session.insertContent(content);

If there is no URI extension or you use an extension that is not mapped to JSON, you can explicitly specify JSON using ContentCreateOptions.setFormat. For example:

ContentCreateOptions options = new ContentCreateOptions();
options.setFormat(DocumentFormat.JSON);
Content content = ContentFactory.newContent(uri, inputFile, options);

The following code snippet inserts a JSON document into the database using an in-memory String representation of the contents:

ContentSource cs = ContentSourceFactory.newContentSource(SERVER_URI);
Session session = cs.newSession();
String uri = "/xcc/fromString.json";
String data = "{\"num\":1, \"arr\":[0, 1], \"str\":\"value\"}";
ContentCreateOptions options = ContentCreateOptions.newJsonInstance();
Content content = ContentFactory.newContent(uri, data, options);
session.insertContent(content);

You can also use Jackson to build up JSON content, and then pass a Jackson JsonNode in to ContentFactory.newJsonContent. To learn more about Jackson, see https://github.com/FasterXML/jackson-doc.