Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
Bedrock Mission!

Learn more

View all

Sign in to view all badges

SOLVED

Iterating through resources and creating a json for a page in AEM 6.4

Avatar

Level 3

Hi,

I am trying to iterate through the resources inside a page. In my code I am able to get the resource but while iterating i only managed to get the last component inside the page. I need to get each resource and its properties so that I can write a json for each resource. The snippet which i have written is as follows:

protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException

{

response.setContentType("application/json");

        response.setCharacterEncoding("utf-8");

       

resolver = request.getResourceResolver();

session = resolver.adaptTo(Session.class);

gson = new Gson();

gsonwriter = gson.newJsonWriter(response.getWriter());

RequestPathInfo requestPathInfo = request.getRequestPathInfo();

Resource res = request.getResourceResolver().getResource(requestPathInfo.getResourcePath());

Resource res2 = res.getChild("parcontent");

Iterator<Resource> resit = res2.listChildren();

{

while(resit.hasNext())

{

Resource res3 = resit.next();

str = res3.getName().toString();

LOG.info("Resource is ::" + res);

ValueMap property = res3.adaptTo(ValueMap.class);

text = property.get("text", String.class);

LOG.info("Property of resource is ::" + text);

props.add(str);

gsonwriter.beginObject();

gsonwriter.name(str).value(text);

gsonwriter.endObject();

}

}

try

{

response.getWriter().println(str1);

response.getWriter().println(text);

}

Jörg Hohsmacdonald2008 Feike Visser

Can anyone please provide a snippet as to how can I iterate inside the resources of a page?

1 Accepted Solution

Avatar

Correct answer by
Employee Advisor

You need to create a recursive method which traverses down the resource tree. You can find an quite extensive example in the JSON renderer of the DefaultGetServlet of Sling, which does the same functionality.

sling-org-apache-sling-servlets-get/JsonRenderer.java at master · apache/sling-org-apache-sling-serv...

HTH,

Jörg

View solution in original post

1 Reply

Avatar

Correct answer by
Employee Advisor

You need to create a recursive method which traverses down the resource tree. You can find an quite extensive example in the JSON renderer of the DefaultGetServlet of Sling, which does the same functionality.

sling-org-apache-sling-servlets-get/JsonRenderer.java at master · apache/sling-org-apache-sling-serv...

HTH,

Jörg