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