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.util.Map;
17
18 import org.eclipse.jetty.util.Loader;
19 import org.eclipse.jetty.util.ajax.JSON.Convertor;
20 import org.eclipse.jetty.util.ajax.JSON.Output;
21
22 public class JSONPojoConvertorFactory implements JSON.Convertor
23 {
24 private final JSON _json;
25 private final boolean _fromJson;
26
27 public JSONPojoConvertorFactory(JSON json)
28 {
29 if (json==null)
30 {
31 throw new IllegalArgumentException();
32 }
33 _json=json;
34 _fromJson=true;
35 }
36
37 /* ------------------------------------------------------------ */
38 /**
39 * @param json The JSON instance to use
40 * @param fromJSON If true, the class name of the objects is included
41 * in the generated JSON and is used to instantiate the object when
42 * JSON is parsed (otherwise a Map is used).
43 */
44 public JSONPojoConvertorFactory(JSON json,boolean fromJSON)
45 {
46 if (json==null)
47 {
48 throw new IllegalArgumentException();
49 }
50 _json=json;
51 _fromJson=fromJSON;
52 }
53
54 /* ------------------------------------------------------------ */
55 public void toJSON(Object obj, Output out)
56 {
57 String clsName=obj.getClass().getName();
58 Convertor convertor=_json.getConvertorFor(clsName);
59 if (convertor==null)
60 {
61 try
62 {
63 Class cls=Loader.loadClass(JSON.class,clsName);
64 convertor=new JSONPojoConvertor(cls,_fromJson);
65 _json.addConvertorFor(clsName, convertor);
66 }
67 catch (ClassNotFoundException e)
68 {
69 e.printStackTrace();
70 }
71 }
72 if (convertor!=null)
73 {
74 convertor.toJSON(obj, out);
75 }
76 }
77
78 public Object fromJSON(Map object)
79 {
80 Map map=object;
81 String clsName=(String)map.get("class");
82 if (clsName!=null)
83 {
84 Convertor convertor=_json.getConvertorFor(clsName);
85 if (convertor==null)
86 {
87 try
88 {
89 Class cls=Loader.loadClass(JSON.class,clsName);
90 convertor=new JSONPojoConvertor(cls,_fromJson);
91 _json.addConvertorFor(clsName, convertor);
92 }
93 catch (ClassNotFoundException e)
94 {
95 e.printStackTrace();
96 }
97 }
98 if (convertor!=null)
99 {
100 return convertor.fromJSON(object);
101 }
102 }
103 return map;
104 }
105 }