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