2 * Copyright 2018-2020 ZTE Corporation.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.onap.holmes.common.utils;
18 import com.google.gson.Gson;
19 import com.google.gson.GsonBuilder;
20 import com.google.gson.JsonDeserializer;
21 import com.google.gson.JsonObject;
22 import com.google.gson.reflect.TypeToken;
23 import org.apache.commons.lang3.StringUtils;
25 import java.util.List;
28 public class GsonUtil {
29 private static Gson gson = null;
33 gson = new GsonBuilder()
34 .registerTypeAdapter(Integer.class, (JsonDeserializer<Integer>) (json, typeOfT, context) -> {
36 return json.getAsInt();
37 } catch (NumberFormatException e) {
49 public static String beanToJson(Object object) {
50 String gsonString = null;
52 gsonString = gson.toJson(object);
57 public static <T> T jsonToBean(String gsonString, Class<T> cls) {
60 t = gson.fromJson(gsonString, cls);
65 public static <T> List<T> jsonToList(String gsonString, Class<T> cls) {
68 list = gson.fromJson(gsonString, TypeToken.getParameterized(List.class, cls).getType());
73 public static <T> List<Map<String, T>> jsonToListMaps(String gsonString, Class<T> cls) {
74 List<Map<String, T>> list = null;
76 list = gson.fromJson(gsonString,
77 TypeToken.getParameterized(List.class,
78 TypeToken.getParameterized(Map.class, String.class, cls).getType()
85 public static <T> Map<String, T> jsonToMap(String gsonString, Class<T> cls) {
86 Map<String, T> map = null;
88 map = gson.fromJson(gsonString, TypeToken.getParameterized(Map.class, String.class, cls).getType());
93 public static String getAsString(JsonObject o, String field) {
97 field = StringUtils.EMPTY;
100 if (o.has(field) && !o.get(field).isJsonNull()) {
101 ret = o.get(field).getAsString();
106 public static long getAsLong(JsonObject o, String field) {
110 field = StringUtils.EMPTY;
113 if (o.has(field) && !o.get(field).isJsonNull()) {
114 ret = o.get(field).getAsLong();
119 public static int getAsInt(JsonObject o, String field) {
123 field = StringUtils.EMPTY;
126 if (o.has(field) && !o.get(field).isJsonNull()) {
127 ret = o.get(field).getAsInt();