Tuesday, September 29, 2015

org.apache.sling.commons.json.JSONException: Misplaced array - JSONWriter

org.apache.sling.commons.json.JSONException: Misplaced array - JSONWriter

The Misplaced array exception is thrown,While we are trying to create the JSON Array of objects from the servlet using - org.apache.sling.commons.json.io.JSONWriter.

Code:-

JSONWriter writer=new JSONWriter(response.getWriter());
try {
writer.object();
writer.key("authorName").value("test");
writer.key("biography").value("test");
writer.key("image").value("test");
writer.array();
writer.object();
writer.key("authorName").value("test");
writer.key("biography").value("test");
writer.endObject();
writer.endArray();
writer.endObject();
} catch (JSONException e) {

}

The root cause of the exception is not providing the key for initialized array(there will be different scenarios we will receive this exception)

To fix the issue as shown below in the code, add the key before starting the array.

JSONWriter writer=new JSONWriter(response.getWriter());
try {
writer.object();
writer.key("authorName").value("test");
writer.key("biography").value("test");
writer.key("image").value("test");
writer.key("list");
writer.array();
writer.object();
writer.key("authorName").value("test");
writer.key("biography").value("test");
writer.endObject();
writer.endArray();
writer.endObject();
} catch (JSONException e) {

}  

O/P

{"authorName":"test","biography":"test","image":"test","list":[{"authorName":"test","biography":"test"}]}       



No comments:

Post a Comment