Converting AEM/Sling Resources to JSON

Adobe Experience Manager | AEM/CQ | Apache Sling

Converting AEM/Sling Resources to JSON

You can easily convert an AEM Page, Sling Resource, or JCR Node to JSON using the class. This simply but useful utility allows you to dump a Node into a JSONObject. It also allows you to dump the Node into a JSON string into a PrintWriter for use in servlets for example.

The constructor accepts a Set of Strings representing JCR properties to exclude from the JSON output. You may want to ignore the standard cq:*, sling:* and jcr:* properties while allowing only your custom properties to populate the JSON.

The overloaded dump methods allow you to pass in the recursion level similar to how you would use a selector when making AJAX calls to the Default Get Servlet. Just as you can cURL /content/geometrixx/en.json, /content/geometrixx/en.1.json and /content/geometrixx/en.-1.json, you can pass in a positive integer for the recursion level as well as -1 for infinite recursion.

Likewise, just as you can cURL /content/geometrixx/en.tidy.json, you can specify whether you want the JSON output nicely formatted or not.

The following examples demonstrate the JsonItemWriter utilizing a PrintWriter in a servlet and a JSONObject in a standard Java class.