1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.springframework.extensions.webscripts.json;
20
21 import java.util.HashMap;
22 import java.util.Map;
23
24 import org.json.JSONArray;
25 import org.json.JSONObject;
26 import org.springframework.extensions.surf.util.Content;
27 import org.springframework.extensions.webscripts.Format;
28 import org.springframework.extensions.webscripts.FormatReader;
29 import org.springframework.extensions.webscripts.WebScriptException;
30 import org.springframework.extensions.webscripts.WebScriptRequest;
31 import org.springframework.extensions.webscripts.WebScriptResponse;
32
33
34
35
36
37
38 public class JSONReader implements FormatReader<Object>
39 {
40
41
42
43 public Class<? extends Object> getDestinationClass()
44 {
45 return Object.class;
46 }
47
48
49
50
51 public String getSourceMimetype()
52 {
53 return Format.JSON.mimetype();
54 }
55
56
57
58
59 public Object read(WebScriptRequest req)
60 {
61 Content content = req.getContent();
62 if (content == null)
63 {
64 throw new WebScriptException("Failed to convert request to JSON");
65 }
66
67 Object result = null;
68 try
69 {
70 String jsonString = content.getContent();
71 if (jsonString.startsWith("[") == true)
72 {
73 result = new JSONArray(jsonString);
74 }
75 else
76 {
77 result = new JSONObject(jsonString);
78 }
79 }
80 catch (Exception exception)
81 {
82 throw new WebScriptException("Failed to convert request to JSON", exception);
83 }
84 return result;
85 }
86
87
88
89
90 public Map<String, Object> createScriptParameters(WebScriptRequest req, WebScriptResponse res)
91 {
92 Map<String, Object> params = new HashMap<String, Object>();
93 params.put("json", read(req));
94 return params;
95 }
96 }