extensions/net.sf.basedb.otp/trunk/src/net/sf/basedb/otp/JsonUtil.java

Code
Comments
Other
Rev Date Author Line
4851 14 Jun 18 nicklas 1 package net.sf.basedb.otp;
4851 14 Jun 18 nicklas 2
4851 14 Jun 18 nicklas 3 import java.io.BufferedReader;
4851 14 Jun 18 nicklas 4 import java.io.IOException;
4851 14 Jun 18 nicklas 5 import java.io.InputStreamReader;
4851 14 Jun 18 nicklas 6 import java.io.Reader;
4851 14 Jun 18 nicklas 7 import java.nio.charset.Charset;
4851 14 Jun 18 nicklas 8
4851 14 Jun 18 nicklas 9 import javax.servlet.http.HttpServletRequest;
4851 14 Jun 18 nicklas 10 import javax.servlet.http.HttpServletResponse;
4851 14 Jun 18 nicklas 11
4851 14 Jun 18 nicklas 12
4851 14 Jun 18 nicklas 13 import org.json.simple.JSONObject;
4851 14 Jun 18 nicklas 14 import org.json.simple.parser.JSONParser;
4851 14 Jun 18 nicklas 15 import org.json.simple.parser.ParseException;
4851 14 Jun 18 nicklas 16
4851 14 Jun 18 nicklas 17 /**
4851 14 Jun 18 nicklas 18   Utility functions for JSON.
4851 14 Jun 18 nicklas 19   @since 1.0
4851 14 Jun 18 nicklas 20 */
4851 14 Jun 18 nicklas 21 public class JsonUtil 
4851 14 Jun 18 nicklas 22 {
4851 14 Jun 18 nicklas 23   /**
4851 14 Jun 18 nicklas 24     Set proper response headers for returning a JSON response.
4851 14 Jun 18 nicklas 25     This sets the content type to: application/json;charset=UTF8
4851 14 Jun 18 nicklas 26     and disable caching of the responses.
4851 14 Jun 18 nicklas 27   */
4851 14 Jun 18 nicklas 28   public static void setJsonResponseHeaders(HttpServletResponse resp)
4851 14 Jun 18 nicklas 29   {
4851 14 Jun 18 nicklas 30     resp.setContentType("application/json");
4851 14 Jun 18 nicklas 31     resp.setCharacterEncoding("UTF-8");
4851 14 Jun 18 nicklas 32     resp.setHeader("Cache-Control", "no-cache, max-age=0");
4851 14 Jun 18 nicklas 33   }
4851 14 Jun 18 nicklas 34
4851 14 Jun 18 nicklas 35   /**
4851 14 Jun 18 nicklas 36     Parse the request as JSON data.
4851 14 Jun 18 nicklas 37   */
4851 14 Jun 18 nicklas 38   public static JSONObject parseRequest(HttpServletRequest request)
4851 14 Jun 18 nicklas 39     throws IOException, ParseException
4851 14 Jun 18 nicklas 40   {
4851 14 Jun 18 nicklas 41     Reader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), Charset.forName("UTF-8")));
4851 14 Jun 18 nicklas 42     JSONObject json = (JSONObject)new JSONParser().parse(reader);
4851 14 Jun 18 nicklas 43     return json;
4851 14 Jun 18 nicklas 44   }
4851 14 Jun 18 nicklas 45   
4851 14 Jun 18 nicklas 46 }