1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.apache.struts2.rest.handler;
23
24 import net.sf.json.JSONArray;
25 import net.sf.json.JSONObject;
26 import net.sf.json.JsonConfig;
27
28 import java.io.IOException;
29 import java.io.Reader;
30 import java.io.Writer;
31 import java.util.Collection;
32
33 /***
34 * Handles JSON content using json-lib
35 */
36 public class JsonLibHandler implements ContentTypeHandler {
37
38 public void toObject(Reader in, Object target) throws IOException {
39 StringBuilder sb = new StringBuilder();
40 char[] buffer = new char[1024];
41 int len = 0;
42 while ((len = in.read(buffer)) > 0) {
43 sb.append(buffer, 0, len);
44 }
45 if (target != null && sb.length() > 0 && sb.charAt(0) == '[') {
46 JSONArray jsonArray = JSONArray.fromObject(sb.toString());
47 if (target.getClass().isArray()) {
48 JSONArray.toArray(jsonArray, target, new JsonConfig());
49 } else {
50 JSONArray.toList(jsonArray, target, new JsonConfig());
51 }
52
53 } else {
54 JSONObject jsonObject = JSONObject.fromObject(sb.toString());
55 JSONObject.toBean(jsonObject, target, new JsonConfig());
56 }
57 }
58
59 public String fromObject(Object obj, String resultCode, Writer stream) throws IOException {
60 if (obj != null) {
61 if (isArray(obj)) {
62 JSONArray jsonArray = JSONArray.fromObject(obj);
63 stream.write(jsonArray.toString());
64 } else {
65 JSONObject jsonObject = JSONObject.fromObject(obj);
66 stream.write(jsonObject.toString());
67 }
68 }
69 return null;
70
71
72 }
73
74 private boolean isArray(Object obj) {
75 return obj instanceof Collection || obj.getClass().isArray();
76 }
77
78 public String getContentType() {
79 return "text/javascript";
80 }
81
82 public String getExtension() {
83 return "json";
84 }
85 }