Add CoAP over Websocket interface in cloud
[platform/upstream/iotivity.git] / cloud / stack / src / main / java / org / iotivity / cloud / util / JSONUtil.java
1 /*
2  * //******************************************************************
3  * //
4  * // Copyright 2016 Samsung Electronics All Rights Reserved.
5  * //
6  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7  * //
8  * // Licensed under the Apache License, Version 2.0 (the "License");
9  * // you may not use this file except in compliance with the License.
10  * // You may obtain a copy of the License at
11  * //
12  * //      http://www.apache.org/licenses/LICENSE-2.0
13  * //
14  * // Unless required by applicable law or agreed to in writing, software
15  * // distributed under the License is distributed on an "AS IS" BASIS,
16  * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * // See the License for the specific language governing permissions and
18  * // limitations under the License.
19  * //
20  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21  */
22 package org.iotivity.cloud.util;
23
24 import java.io.IOException;
25
26 import com.fasterxml.jackson.core.JsonProcessingException;
27 import com.fasterxml.jackson.databind.ObjectMapper;
28
29 /**
30  * 
31  * This class provides utility for parsing JSON object and converting data to
32  * JSON string.
33  * 
34  */
35 public class JSONUtil<T> {
36
37     private static ObjectMapper mapper = new ObjectMapper();
38
39     @SuppressWarnings("unchecked")
40     public T parseJSON(byte[] data, Class<? extends Object> class1) {
41
42         if (data == null)
43             return null;
44
45         T parsedData = null;
46
47         try {
48             parsedData = (T) mapper.readValue(data, class1);
49
50         } catch (IOException ioe) {
51             ioe.printStackTrace();
52         }
53
54         return parsedData;
55     }
56
57     public T parseJSON(String data, Class<? extends Object> class1) {
58
59         if (data == null || data.equals(""))
60             return null;
61
62         T parsedData = null;
63
64         try {
65             parsedData = (T) mapper.readValue(data, class1);
66
67         } catch (IOException ioe) {
68             ioe.printStackTrace();
69         }
70
71         return parsedData;
72     }
73
74     public T writeJSON(Object data) {
75         if (data == null)
76             return null;
77
78         T json = null;
79         try {
80             json = (T) mapper.writeValueAsString(data);
81         } catch (JsonProcessingException e) {
82             e.printStackTrace();
83         }
84
85         if (json == null)
86             json = (T) "{}";
87
88         return json;
89     }
90 }