1
2
3
4
5
6
7
8
9
10
11
12
13
14 package org.mortbay.util.ajax;
15
16 import java.util.Map;
17
18 import org.mortbay.util.Loader;
19 import org.mortbay.util.ajax.JSON.Convertor;
20 import org.mortbay.util.ajax.JSON.Output;
21
22 public class JSONPojoConvertorFactory implements JSON.Convertor
23 {
24 private JSON _json=null;
25
26 public JSONPojoConvertorFactory(JSON json)
27 {
28 if (json==null)
29 {
30 throw new IllegalArgumentException();
31 }
32 _json=json;
33 }
34
35 public void toJSON(Object obj, Output out)
36 {
37 String clsName=obj.getClass().getName();
38 Convertor convertor=_json.getConvertorFor(clsName);
39 if (convertor==null)
40 {
41 try
42 {
43 Class cls=Loader.loadClass(JSON.class,clsName);
44 convertor=new JSONPojoConvertor(cls);
45 _json.addConvertorFor(clsName, convertor);
46 }
47 catch (ClassNotFoundException e)
48 {
49 e.printStackTrace();
50 }
51 }
52 if (convertor!=null&&obj.getClass()!=Object.class)
53 {
54 convertor.toJSON(obj, out);
55 }
56 else
57 {
58 out.add(obj.toString());
59 }
60 }
61
62 public Object fromJSON(Map object)
63 {
64 Map map=object;
65 String clsName=(String)map.get("class");
66 if (clsName!=null)
67 {
68 Convertor convertor=_json.getConvertorFor(clsName);
69 if (convertor==null)
70 {
71 try
72 {
73 Class cls=Loader.loadClass(JSON.class,clsName);
74 convertor=new JSONPojoConvertor(cls);
75 _json.addConvertorFor(clsName, convertor);
76 }
77 catch (ClassNotFoundException e)
78 {
79 e.printStackTrace();
80 }
81 }
82 if (convertor!=null&&!clsName.equals(Object.class.getName()))
83 {
84 return convertor.fromJSON(object);
85 }
86 }
87 return map;
88 }
89 }