May 10, 2020
Estimated Post Reading Time ~

TidyJSONWriter Tutorial

JSONWriter provides a quick and convenient way of producing JSON text. The texts produced strictly conform to JSON syntax rules. No whitespace is added, so the results are ready for transmission or storage. Each instance of JSONWriter can produce one JSON text.

TidyJSONWriter Sample code:

<%@page session="false"%>
<%@include file="/libs/foundation/global.jsp" %>
<%@page contentType="application/json" pageEncoding="utf-8" import="com.day.cq.commons.TidyJSONWriter;" %>
<%

    String elements[] = {"Java","AEM","JCR","Codermagnet"};  
    TidyJSONWriter w = new TidyJSONWriter(out);              
    
    w.setTidy(true); //If true, output will be pretty printed
    w.array();       // Start array

        for(int i=0;i<elements.length;i++)
        {
            w.object();   //Every time a new object is created
            w.key("index").value(""+(i+1));
            w.key("value").value(elements[i]);
            w.endObject();
        }
    w.endArray();
%>

Output:

[{
    "index": "1",
    "value": "Java"
  },{
    "index": "2",
    "value": "AEM"
  },{
    "index": "3",
    "value": "JCR"
  },{
    "index": "4",
    "value": "Codermagnet"
  }
]


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.