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