View Javadoc

1   //========================================================================
2   //Copyright 2004-2008 Mort Bay Consulting Pty. Ltd.
3   //------------------------------------------------------------------------
4   //Licensed under the Apache License, Version 2.0 (the "License");
5   //you may not use this file except in compliance with the License.
6   //You may obtain a copy of the License at 
7   //http://www.apache.org/licenses/LICENSE-2.0
8   //Unless required by applicable law or agreed to in writing, software
9   //distributed under the License is distributed on an "AS IS" BASIS,
10  //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11  //See the License for the specific language governing permissions and
12  //limitations under the License.
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   * Convert an {@link Enum} to JSON.
27   * If fromJSON is true in the constructor, the JSON generated will
28   * be of the form {class="com.acme.TrafficLight",value="Green"}
29   * If fromJSON is false, then only the string value of the enum is generated.
30   * @author gregw
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  }