Skip to content

Instantly share code, notes, and snippets.

@nateyolles
Created December 9, 2015 04:44
Show Gist options
  • Save nateyolles/c683f8b39ca1e4688b38 to your computer and use it in GitHub Desktop.
Save nateyolles/c683f8b39ca1e4688b38 to your computer and use it in GitHub Desktop.
Easily turn an AEM/Sling Resource/Node into a JSONObject
package com.nateyolles.aem;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.apache.sling.commons.json.jcr.JsonItemWriter;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import java.io.StringWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Example of how to easily turn a Node into a JSONObject.
*/
public class ConvertResourceToJSON {
/** The logger */
private static final Logger LOGGER = LoggerFactory.getLogger(ConvertResourceToJSON.class);
/**
* Get the JSON representation of a Resource
*
* @param resolver Resolver to get resource
* @param resource Resource to turn into JSON
* @return JSON representation of the resource
*/
public JSONObject resourceToJSON(final ResourceResolver resolver, final Resource resource) {
final Node node = resource.adaptTo(Node.class);
final StringWriter stringWriter = new StringWriter();
final JsonItemWriter jsonWriter = new JsonItemWriter(null);
JSONObject jsonObject = null;
try {
/* Get JSON with no limit to recursion depth. */
jsonWriter.dump(node, stringWriter, -1);
jsonObject = new JSONObject(stringWriter.toString());
} catch (RepositoryException | JSONException e) {
LOGGER.error("Could not create JSON", e);
}
return jsonObject;
}
}
@cmrockwell
Copy link

cmrockwell commented Jul 12, 2018

Thanks for posting this. I've been looking for this functionality, and it seems it was (or is?) part of the Sling API's. I'm curious whether you think your code is the best way or whether you've found API's that do the job.

https://sling.apache.org/apidocs/sling8/org/apache/sling/commons/json/jcr/JsonJcrNode.html#JsonJcrNode(javax.jcr.Node

https://helpx.adobe.com/experience-manager/6-3/sites/developing/using/reference-materials/javadoc/index.html?org/apache/sling/commons/json/jcr/JsonJcrNode.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment