1   package org.mortbay.util.ajax;
2   
3   import java.lang.reflect.Method;
4   import java.util.Map;
5   
6   import org.mortbay.log.Log;
7   import org.mortbay.util.Loader;
8   import org.mortbay.util.ajax.JSON.Output;
9   
10  /* ------------------------------------------------------------ */
11  /**
12   * Convert an {@link Enum} to JSON.
13   * If fromJSON is true in the constructor, the JSON generated will
14   * be of the form {class="com.acme.TrafficLight",value="Green"}
15   * If fromJSON is false, then only the string value of the enum is generated.
16   * @author gregw
17   *
18   */
19  public class JSONEnumConvertor implements JSON.Convertor
20  {
21      private boolean _fromJSON;
22      private Method _valueOf;
23      {
24          try
25          {
26              Class e = Loader.loadClass(getClass(),"java.lang.Enum");
27              _valueOf=e.getMethod("valueOf",new Class[]{Class.class,String.class});
28          }
29          catch(Exception e)
30          {
31              throw new RuntimeException("!Enums",e);
32          }
33      }
34  
35      public JSONEnumConvertor()
36      {
37          this(false);
38      }
39      
40      public JSONEnumConvertor(boolean fromJSON)
41      {
42          _fromJSON=fromJSON;
43      }
44      
45      public Object fromJSON(Map map)
46      {
47          if (!_fromJSON)
48              throw new UnsupportedOperationException();
49          try
50          {
51              Class c=Loader.loadClass(getClass(),(String)map.get("class"));
52              return _valueOf.invoke(null,new Object[]{c,map.get("value")});
53          }
54          catch(Exception e)
55          {
56              Log.warn(e);  
57          }
58          return null;
59      }
60  
61      public void toJSON(Object obj, Output out)
62      {
63          if (_fromJSON)
64          {
65              out.addClass(obj.getClass());
66              out.add("value",obj.toString());
67          }
68          else
69          {
70              out.add(obj.toString());
71          }
72      }
73  
74  }