Tuesday, October 11, 2011

How to generate JSON in app engine servlet

Well, I was working on pass json to map to draw polygone shape. Easily, I can use stringbuffer to assemble it.but, while I am looking at GSON api, it looks so easy. there is a few things I need to consider.

1. your data type should match with json output. for example, if you are using string, gson will add "" around. so, if you do not want, use long,float, int based on your need.
2. make sure setHtmlSafe = false, if not, it will add unicode that you do not want.
3. make sure your httpserveltresponse = application/json
4. HashMap messages is HashMap of dao object collection. nothing is special here.


public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
    processRequest(request, response);
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
processRequest(request, response);
}

@SuppressWarnings("unchecked")
public void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {


PrintWriter print = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");

DataAct da = new DataAct();
try {
    HashMap messages = da.getNotification();
    JsonWriter writer = new JsonWriter(print);

   

    writer.setHtmlSafe(false);
    writer.setIndent("    ");
    writeMessagesArray(writer, messages);
    writer.close();

     

} catch (ServiceException e) {
e.printStackTrace();
}

 

}


public void writeJsonStream(OutputStream out, HashMap messages) throws IOException {
    JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));

   

    writer.setHtmlSafe(false);
    writer.setIndent("    ");
    writeMessagesArray(writer, messages);
    writer.toString();
    writer.close();
  }

  public void writeMessagesArray(JsonWriter writer, HashMap messages) throws IOException {
    writer.beginArray();

     

    for(int i = 0; i < messages.size(); i++){
    writeMessage(writer, (Notification)messages.get(new Integer(i)));
    }

    writer.endArray();
  }

  public void writeMessage(JsonWriter writer, Notification message) throws IOException {
    writer.beginObject();
    writer.name("id").value(message.getId());
    writer.name("title").value(message.getTitle());
    writer.name("type").value(message.getType());
    writer.name("lat").value(message.getLat());
    writer.name("lon").value(message.getLon());
    writer.name("description").value(message.getDescription());
    writer.name("imgURL").value(message.getImgURL());
    writer.endObject();
  }

MashMap message is collection of :

public class Notification {
private int id;
private String title;
private String description;
private String type;
private float lat;
private float lon;
private String imgURL;
.........

}

0 comments:

Post a Comment