1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   * 
13   */
14  
15  package com.liferay.util.json;
16  
17  import com.liferay.portal.kernel.json.JSONObject;
18  import com.liferay.portal.kernel.log.Log;
19  import com.liferay.portal.kernel.log.LogFactoryUtil;
20  
21  import org.jabsorb.JSONSerializer;
22  import org.jabsorb.serializer.MarshallException;
23  import org.jabsorb.serializer.UnmarshallException;
24  
25  /**
26   * <a href="JSONFactoryUtil.java.html"><b><i>View Source</i></b></a>
27   *
28   * @author Brian Wing Shun Chan
29   */
30  public class JSONFactoryUtil {
31  
32      public static Object deserialize(JSONObject jsonObj) {
33          return _instance._deserialize(jsonObj);
34      }
35  
36      public static Object deserialize(String json) {
37          return _instance._deserialize(json);
38      }
39  
40      public static String serialize(Object obj) {
41          return _instance._serialize(obj);
42      }
43  
44      private JSONFactoryUtil() {
45          _serializer = new JSONSerializer();
46  
47           try {
48               _serializer.registerDefaultSerializers();
49           }
50           catch (Exception e) {
51               _log.error(e, e);
52           }
53      }
54  
55      private Object _deserialize(JSONObject jsonObj) {
56          return _deserialize(jsonObj.toString());
57      }
58  
59      private Object _deserialize(String json) {
60          try {
61              return _serializer.fromJSON(json);
62          }
63          catch (UnmarshallException ue) {
64               _log.error(ue, ue);
65  
66              throw new IllegalStateException("Unable to deserialize oject", ue);
67          }
68      }
69  
70      private String _serialize(Object obj) {
71          try {
72              return _serializer.toJSON(obj);
73          }
74          catch (MarshallException me) {
75              _log.error(me, me);
76  
77              throw new IllegalStateException("Unable to serialize oject", me);
78          }
79      }
80  
81      private static Log _log = LogFactoryUtil.getLog(JSONFactoryUtil.class);
82  
83      private static JSONFactoryUtil _instance = new JSONFactoryUtil();
84  
85      private JSONSerializer _serializer;
86  
87  }