Replace Jackson with GSON
[holmes/common.git] / holmes-actions / src / main / java / org / onap / holmes / common / utils / GsonUtil.java
1 /**
2  * Copyright 2018 ZTE Corporation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.onap.holmes.common.utils;
17
18 import com.google.gson.Gson;
19 import com.google.gson.reflect.TypeToken;
20 import java.util.List;
21 import java.util.Map;
22
23 public class GsonUtil {
24     private static Gson gson = null;
25     static {
26         if (gson == null) {;
27             gson = new Gson();
28         }
29     }
30
31     private GsonUtil() {
32     }
33     public static String beanToJson(Object object) {
34         String gsonString = null;
35         if (gson != null) {
36             gsonString = gson.toJson(object);
37         }
38         return gsonString;
39     }
40
41     public static <T> T jsonToBean(String gsonString, Class<T> cls) {
42         T t = null;
43         if (gson != null) {
44             t = gson.fromJson(gsonString, cls);
45         }
46         return t;
47     }
48
49     public static <T> List<T> GsonToList(String gsonString, Class<T> cls) {
50         List<T> list = null;
51         if (gson != null) {
52             list = gson.fromJson(gsonString, new TypeToken<List<T>>() {
53             }.getType());
54         }
55         return list;
56     }
57
58     public static <T> List<Map<String, T>> GsonToListMaps(String gsonString) {
59         List<Map<String, T>> list = null;
60         if (gson != null) {
61             list = gson.fromJson(gsonString,
62                     new TypeToken<List<Map<String, T>>>() {
63                     }.getType());
64         }
65         return list;
66     }
67
68     public static <T> Map<String, T> GsonToMaps(String gsonString) {
69         Map<String, T> map = null;
70         if (gson != null) {
71             map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {
72             }.getType());
73         }
74         return map;
75     }
76 }