Jun 13, 2012

GAE - JSON implementation

Most of us also looking how to implement JSON on GAE. In one blog, posted how and he made it by create a POJO or maybe this was also called entity. Here's the impementation:
Class Response{
 public enum Status {
  ERROR, OK, WARNING
 }
 private Status status;
 private String message;

 public Response(Status status, String message)
 {
  this.status = status;
  this.message = message;
 }
 public String toJson() {
  Gson gson = new Gson();
  String json = gson.toJson(this);
  return json;
 }
 public static Response constructFromJson(String json)
 {
  Gson gson = new Gson();
  return gson.fromJson(json, Response.class);
 }
}
Here's how he implement:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException
{
 resp.setContentType("text/plain");
 //do your work here
 ...
 PrintWriter out = resp.getWriter();
 Response response = new Response(Response.Status.OK, "A success!");
 out.print(response.toJson());
}
Here's response looks:
{“status”:”OK”,”message”:”A success”}

TODO: Maybe someone ask. What if I want a array. Maybe try to looks at it and see how the implementation. This maybe we create a ArrayList properity or array it self. :) Give credit to nadacode.com

No comments: