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 public class JSONObjectConvertor implements JSON.Convertor
35 {
36 private boolean _fromJSON;
37 private Set _excluded=null;
38
39 public JSONObjectConvertor()
40 {
41 _fromJSON=false;
42 }
43
44 public JSONObjectConvertor(boolean fromJSON)
45 {
46 _fromJSON=fromJSON;
47 }
48
49
50
51
52
53
54 public JSONObjectConvertor(boolean fromJSON,String[] excluded)
55 {
56 _fromJSON=fromJSON;
57 if (excluded!=null)
58 _excluded=new HashSet(Arrays.asList(excluded));
59 }
60
61 public Object fromJSON(Map map)
62 {
63 if (_fromJSON)
64 throw new UnsupportedOperationException();
65 return map;
66 }
67
68 public void toJSON(Object obj, Output out)
69 {
70 try
71 {
72 Class c=obj.getClass();
73
74 if (_fromJSON)
75 out.addClass(obj.getClass());
76
77 Method[] methods = obj.getClass().getMethods();
78
79 for (int i=0;i<methods.length;i++)
80 {
81 Method m=methods[i];
82 if (!Modifier.isStatic(m.getModifiers()) &&
83 m.getParameterTypes().length==0 &&
84 m.getReturnType()!=null &&
85 m.getDeclaringClass()!=Object.class)
86 {
87 String name=m.getName();
88 if (name.startsWith("is"))
89 name=name.substring(2,3).toLowerCase(Locale.ENGLISH)+name.substring(3);
90 else if (name.startsWith("get"))
91 name=name.substring(3,4).toLowerCase(Locale.ENGLISH)+name.substring(4);
92 else
93 continue;
94
95 if (includeField(name,obj,m))
96 out.add(name, m.invoke(obj,(Object[])null));
97 }
98 }
99 }
100 catch (Throwable e)
101 {
102 throw new IllegalArgumentException(e);
103 }
104 }
105
106 protected boolean includeField(String name, Object o, Method m)
107 {
108 return _excluded==null || !_excluded.contains(name);
109 }
110
111 }