1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.mortbay.util.ajax;
16
17 import java.lang.reflect.Method;
18 import java.lang.reflect.Modifier;
19 import java.util.Arrays;
20 import java.util.HashSet;
21 import java.util.Map;
22 import java.util.Set;
23
24 import org.mortbay.util.ajax.JSON.Output;
25
26
27
28
29
30
31
32
33 public class JSONObjectConvertor implements JSON.Convertor
34 {
35 private boolean _fromJSON;
36 private Set _excluded=null;
37
38 public JSONObjectConvertor()
39 {
40 _fromJSON=false;
41 }
42
43 public JSONObjectConvertor(boolean fromJSON)
44 {
45 _fromJSON=fromJSON;
46 }
47
48
49
50
51
52
53 public JSONObjectConvertor(boolean fromJSON,String[] excluded)
54 {
55 _fromJSON=fromJSON;
56 if (excluded!=null)
57 _excluded=new HashSet(Arrays.asList(excluded));
58 }
59
60 public Object fromJSON(Map map)
61 {
62 if (_fromJSON)
63 throw new UnsupportedOperationException();
64 return map;
65 }
66
67 public void toJSON(Object obj, Output out)
68 {
69 try
70 {
71 Class c=obj.getClass();
72
73 if (_fromJSON)
74 out.addClass(obj.getClass());
75
76 Method[] methods = obj.getClass().getMethods();
77
78 for (int i=0;i<methods.length;i++)
79 {
80 Method m=methods[i];
81 if (!Modifier.isStatic(m.getModifiers()) &&
82 m.getParameterTypes().length==0 &&
83 m.getReturnType()!=null &&
84 m.getDeclaringClass()!=Object.class)
85 {
86 String name=m.getName();
87 if (name.startsWith("is"))
88 name=name.substring(2,3).toLowerCase()+name.substring(3);
89 else if (name.startsWith("get"))
90 name=name.substring(3,4).toLowerCase()+name.substring(4);
91 else
92 continue;
93
94 if (includeField(name,obj,m))
95 out.add(name, m.invoke(obj,(Object[])null));
96 }
97 }
98 }
99 catch (Throwable e)
100 {
101 throw new RuntimeException("Illegal argument", e);
102 }
103 }
104
105 protected boolean includeField(String name, Object o, Method m)
106 {
107 return _excluded==null || !_excluded.contains(name);
108 }
109
110 }