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