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