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.util.Map;
19
20 import org.mortbay.log.Log;
21 import org.mortbay.util.Loader;
22 import org.mortbay.util.ajax.JSON.Output;
23
24
25
26
27
28
29
30
31
32
33 public class JSONEnumConvertor implements JSON.Convertor
34 {
35 private boolean _fromJSON;
36 private Method _valueOf;
37 {
38 try
39 {
40 Class e = Loader.loadClass(getClass(),"java.lang.Enum");
41 _valueOf=e.getMethod("valueOf",new Class[]{Class.class,String.class});
42 }
43 catch(Exception e)
44 {
45 throw new RuntimeException("!Enums",e);
46 }
47 }
48
49 public JSONEnumConvertor()
50 {
51 this(false);
52 }
53
54 public JSONEnumConvertor(boolean fromJSON)
55 {
56 _fromJSON=fromJSON;
57 }
58
59 public Object fromJSON(Map map)
60 {
61 if (!_fromJSON)
62 throw new UnsupportedOperationException();
63 try
64 {
65 Class c=Loader.loadClass(getClass(),(String)map.get("class"));
66 return _valueOf.invoke(null,new Object[]{c,map.get("value")});
67 }
68 catch(Exception e)
69 {
70 Log.warn(e);
71 }
72 return null;
73 }
74
75 public void toJSON(Object obj, Output out)
76 {
77 if (_fromJSON)
78 {
79 out.addClass(obj.getClass());
80 out.add("value",obj.toString());
81 }
82 else
83 {
84 out.add(obj.toString());
85 }
86 }
87
88 }