1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
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  }