2 * Copyright 2018-2021 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.*;
19 import com.google.gson.reflect.TypeToken;
20 import org.apache.commons.lang3.StringUtils;
22 import java.util.Date;
23 import java.util.List;
26 public class GsonUtil {
27 private static Gson gson = null;
31 gson = new GsonBuilder()
32 .registerTypeAdapter(Integer.class, (JsonDeserializer<Integer>) (json, typeOfT, context) -> {
34 return json.getAsInt();
35 } catch (NumberFormatException e) {
39 .registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (jsonElement, type, jsonDeserializationContext) -> {
41 return jsonElement == null ? null : new Date(jsonElement.getAsLong());
42 } catch (NumberFormatException e) {
46 .registerTypeAdapter(Date.class, (JsonSerializer<Date>) (date, type, jsonSerializationContext)
47 -> date == null ? null : new JsonPrimitive(date.getTime()))
56 public static String beanToJson(Object object) {
57 String gsonString = null;
59 gsonString = gson.toJson(object);
64 public static <T> T jsonToBean(String gsonString, Class<T> cls) {
67 t = gson.fromJson(gsonString, cls);
72 public static <T> List<T> jsonToList(String gsonString, Class<T> cls) {
75 list = gson.fromJson(gsonString, TypeToken.getParameterized(List.class, cls).getType());
80 public static <T> List<Map<String, T>> jsonToListMaps(String gsonString, Class<T> cls) {
81 List<Map<String, T>> list = null;
83 list = gson.fromJson(gsonString,
84 TypeToken.getParameterized(List.class,
85 TypeToken.getParameterized(Map.class, String.class, cls).getType()
92 public static <T> Map<String, T> jsonToMap(String gsonString, Class<T> cls) {
93 Map<String, T> map = null;
95 map = gson.fromJson(gsonString, TypeToken.getParameterized(Map.class, String.class, cls).getType());
100 public static String getAsString(JsonObject o, String field) {
104 field = StringUtils.EMPTY;
107 if (o.has(field) && !o.get(field).isJsonNull()) {
108 ret = o.get(field).getAsString();
113 public static long getAsLong(JsonObject o, String field) {
117 field = StringUtils.EMPTY;
120 if (o.has(field) && !o.get(field).isJsonNull()) {
121 ret = o.get(field).getAsLong();
126 public static int getAsInt(JsonObject o, String field) {
130 field = StringUtils.EMPTY;
133 if (o.has(field) && !o.get(field).isJsonNull()) {
134 ret = o.get(field).getAsInt();