treefrog
treefrog

Reputation: 1057

How to create a custome json response in adobe CQ?

I want to be able to return a json response with some specific dynamic data. I am having a hard time understanding the steps involved in doing so. This is not for getting the node details that CQ automatically does.

The goal is to have a json response returned with a request like so http:///def/getMyInfo.json

Upvotes: 0

Views: 723

Answers (2)

treefrog
treefrog

Reputation: 1057

I want to access it more like this -without the jcr:content

http://localhost:4502/content/geometrixx/en/mycomponentinstance.json

I created a page mycomponentinstance, that had a sling resource component mycomponentinstance. The component has a file mycomponentinstance.json.jsp with my json response. It also has Page.json, which I guess was key in getting it to recognize the thing.

Upvotes: 0

Francois Cournoyer
Francois Cournoyer

Reputation: 174

If you want to do it at a component level, the way you do it is by creating a JSON.jsp in the component.

in the jsp you would have something like

<%@ page import="org.apache.sling.commons.json.io.*" %>
<%@include file="/libs/foundation/global.jsp" %>
<% 
    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");

    JSONWriter writer = new JSONWriter(response.getWriter());
    writer.object();
    writer.key("Name");
    writer.value("English");
    writer.key("Code");
    writer.value("en");
    writer.endObject();
%>

then if you want to access the json, you'd access it going to something like http://localhost:4502/content/geometrixx/en/jcr:content/mycomponentinstance.json

If you want it to be more generic, you can add the JSON.jsp to a page component instead of a normal component, then you would need to call http://localhost:4502/content/geometrixx/en/jcr:content.json instead.

Upvotes: 1

Related Questions