How to convert an AEM Node into JSON representation
WE can easily convert an AEM node to its JSON representation by using the
org.apache.sling.commons.json.jcr.JsonItemWriter class.
This can be any type of Node like JCR node, AEM page, sling resource, cq:Page. etc.
The simple code for doing this is
StringWriter stringWriter = new StringWriter();
JsonItemWriter jsonWriter = new JsonItemWriter(null);
jsonWriter.dump(node, stringWriter, -1, true);
String json = stringWriter.toString();
EXAMPLE: 1. Let's suppose we have the following node "/apps/geometrixx-gov/components/logo" that we need to convert to JSON.
2. Now we want to convert it into it's JSON representation.
3. Let's write the main method to do so.
package codermag.net;
import java.io.StringWriter;
import javax.jcr.Node;
import javax.jcr.Repository;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.jackrabbit.core.TransientRepository;
import org.apache.sling.commons.json.jcr.JsonItemWriter;
public class test {
public static void main(String[] args) throws Exception {
Repository repository = new TransientRepository();
repository = JcrUtils.getRepository("http://localhost:4502/crx/server");
Session session = repository.login(new SimpleCredentials("admin","admin".toCharArray()));
// Getting a particular node
Node root = session.getRootNode();
Node subContent = root.getNode("apps/geometrixx-gov/components/logo");
// Iterating over the nodes and printing their names
StringWriter stringWriter = new StringWriter();
JsonItemWriter jsonWriter = new JsonItemWriter(null);
jsonWriter.dump(subContent, stringWriter, -1, true);
String json = stringWriter.toString();
System.out.println(json);
}
}
NOTE: To run the program download the Jack Rabbit Jar File form
http://www.apache.org/dyn/closer.cgi/jackrabbit/2.8.1/jackrabbit-standalone-2.8.1.jar and place it in your project build path.
5. This code will connect to the AEM JCR and get the node. Then it will convert it to JSON.
OUTPUT:
{
"jcr:title": "Logo",
"jcr:created": "Wed Aug 05 2015 07:33:54 GMT+0530",
"jcr:createdBy": "admin",
"jcr:primaryType": "cq:Component",
"sling:resourceSuperType": "foundation/components/logo",
"componentGroup": ".hidden",
"logo.jsp": {
"jcr:created": "Wed Aug 05 2015 07:33:54 GMT+0530",
"jcr:createdBy": "admin",
"jcr:primaryType": "nt:file",
"jcr:content": {
"jcr:lastModifiedBy": "admin",
":jcr:data": 2185,
"jcr:lastModified": "Wed Aug 05 2015 07:33:54 GMT+0530",
"jcr:primaryType": "nt:resource",
"jcr:mimeType": "text/plain",
"jcr:uuid": "b8261ccb-ecd4-4c01-bbe1-fb1371a8c910"
}
}
}
Please go through the JSON data and the screenshot of the LOGO Node to understand better.
No comments:
Post a Comment
If you have any doubts or questions, please let us know.