2 * Copyright 2018 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.JsonDeserializationContext;
21 import com.google.gson.JsonDeserializer;
22 import com.google.gson.JsonElement;
23 import com.google.gson.JsonParseException;
24 import com.google.gson.reflect.TypeToken;
25 import java.lang.reflect.Type;
26 import java.util.List;
29 public class GsonUtil {
30 private static Gson gson = null;
33 gson = new GsonBuilder()
34 .registerTypeAdapter(Integer.class, new JsonDeserializer<Integer>() {
36 public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
38 return json.getAsInt();
39 } catch (NumberFormatException e) {
52 public static String beanToJson(Object object) {
53 String gsonString = null;
55 gsonString = gson.toJson(object);
60 public static <T> T jsonToBean(String gsonString, Class<T> cls) {
63 t = gson.fromJson(gsonString, cls);
68 public static <T> List<T> GsonToList(String gsonString, Class<T> cls) {
71 list = gson.fromJson(gsonString, new TypeToken<List<T>>() {
77 public static <T> List<Map<String, T>> GsonToListMaps(String gsonString) {
78 List<Map<String, T>> list = null;
80 list = gson.fromJson(gsonString,
81 new TypeToken<List<Map<String, T>>>() {
87 public static <T> Map<String, T> GsonToMaps(String gsonString) {
88 Map<String, T> map = null;
90 map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {