Thursday, 31 March 2016

TidyJSONWriter Example (com.day.cq.commons.TidyJSONWriter)

tidyjsonwriter example codermagnet


TidyJSONWriter Example/ TidyJSONWriter Sample/ 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"
  }
]


No comments:

Post a Comment

Coder Magnet
CoderMagnet is full of resources from our daily development activities. It has solutions for common problematic scenarios in technologies like Java 8, AEM, JCR and also occasionally gives you tips on Blogger as well.