Question

I'm trying to get a JCR node as JSON within the context of a Java Class. I was curious if there was an internal API for JCR that will return the Node as a JSON w/ an array of it's child nodes.

A good example would be the output that you would get from making an request to mynode.infinity.json in the browser.

I took at look at JsonJcrNode class, and it does give me what I want, but it excludes the children of the target node.

I'm thinking that I will have to manually get a node and it's children and then iterate through properties and manually create my JSONObject. I was just curious if this has been done already or if there are any other interfaces I'm missing that could help me solve this issue.

thank you,

Brodie

Was it helpful?

Solution

JsonItemWriter class does exactly what you need:

Node node = session.getNode("/content/geometrixx/en/toolbar/contacts");
StringWriter stringWriter = new StringWriter();
JsonItemWriter jsonWriter = new JsonItemWriter(null);
jsonWriter.dump(node, stringWriter, -1, true);
String json = stringWriter.toString();

The dump() method allows to specify recursion level (-1 for infinity) and optionally produces nicely formatted output (pass true as the last parameter).

OTHER TIPS

As recommended by Brodie in the comments of Tomek's response TidyJsonItemWriter should be used (assuming youre working with a project thats using the com.day.cq.commons package). JsonItemWriter is now deprecated.

The code from Tomek is basically the same, just use an instance of TidyJsonItemWriter instead of JsonItemWriter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top