View Javadoc

1   // ========================================================================
2   // Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd.
3   // ------------------------------------------------------------------------
4   // All rights reserved. This program and the accompanying materials
5   // are made available under the terms of the Eclipse Public License v1.0
6   // and Apache License v2.0 which accompanies this distribution.
7   // The Eclipse Public License is available at 
8   // http://www.eclipse.org/legal/epl-v10.html
9   // The Apache License v2.0 is available at
10  // http://www.opensource.org/licenses/apache2.0.php
11  // You may elect to redistribute this code under either of these licenses. 
12  // ========================================================================
13  
14  package org.eclipse.jetty.util.ajax;
15  
16  import java.lang.reflect.Method;
17  import java.util.Map;
18  
19  import org.eclipse.jetty.util.Loader;
20  import org.eclipse.jetty.util.ajax.JSON.Output;
21  import org.eclipse.jetty.util.log.Log;
22  
23  /* ------------------------------------------------------------ */
24  /**
25   * Convert an {@link Enum} to JSON.
26   * If fromJSON is true in the constructor, the JSON generated will
27   * be of the form {class="com.acme.TrafficLight",value="Green"}
28   * If fromJSON is false, then only the string value of the enum is generated.
29   * 
30   *
31   */
32  public class JSONEnumConvertor implements JSON.Convertor
33  {
34      private boolean _fromJSON;
35      private Method _valueOf;
36      {
37          try
38          {
39              Class e = Loader.loadClass(getClass(),"java.lang.Enum");
40              _valueOf=e.getMethod("valueOf",new Class[]{Class.class,String.class});
41          }
42          catch(Exception e)
43          {
44              throw new RuntimeException("!Enums",e);
45          }
46      }
47  
48      public JSONEnumConvertor()
49      {
50          this(false);
51      }
52      
53      public JSONEnumConvertor(boolean fromJSON)
54      {
55          _fromJSON=fromJSON;
56      }
57      
58      public Object fromJSON(Map map)
59      {
60          if (!_fromJSON)
61              throw new UnsupportedOperationException();
62          try
63          {
64              Class c=Loader.loadClass(getClass(),(String)map.get("class"));
65              return _valueOf.invoke(null,new Object[]{c,map.get("value")});
66          }
67          catch(Exception e)
68          {
69              Log.warn(e);  
70          }
71          return null;
72      }
73  
74      public void toJSON(Object obj, Output out)
75      {
76          if (_fromJSON)
77          {
78              out.addClass(obj.getClass());
79              out.add("value",obj.toString());
80          }
81          else
82          {
83              out.add(obj.toString());
84          }
85      }
86  
87  }