Friday, May 30, 2014

How to read JSON data (json request) from http request in a servlet or controller


If you use a javascript AJAX request which sends the http request in JSON data format and not in normal key value pair, you might need this.
One such example is the ExtJS store's, api config. For all the write operations the proxy for create/update/delete (use AJAX) sends the records in json form, in case the reader is defined as json.

Code:

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
  throws ServletException, IOException {
  
 PrintWriter out = response.getWriter();
 StringBuilder jsonString = new StringBuilder();
 
 String jsonToken = null;
 
 BufferedReader reader = request.getReader();
 while ((jsonToken = reader.readLine()) != null){
  jsonString.append(line);
 } 
 // converting the JSON String into a JSONObject, which almost work like a Map  
 try {
  JSONObject requestJsonObject = new JSONObject(jsonString); 
  // JSONObject from JSON Java API from json.org
  System.out.println(requestJsonObject.toString());
 }catch(JSONException jsone){
  jsone.printStackTrace();
 } 
  
 // further processing goes here....
} 

Interesting reads:

No comments:

Post a Comment

Prototype

Prototype is another creation pattern. Intent:  - Intent is to create objects by cloning existing instance  - Specify the kinds of obj...