1 /* Copyright (c) 2019 AT&T Intellectual Property. #
\r
3 # Licensed under the Apache License, Version 2.0 (the "License"); #
\r
4 # you may not use this file except in compliance with the License. #
\r
5 # You may obtain a copy of the License at #
\r
7 # http://www.apache.org/licenses/LICENSE-2.0 #
\r
9 # Unless required by applicable law or agreed to in writing, software #
\r
10 # distributed under the License is distributed on an "AS IS" BASIS, #
\r
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
\r
12 # See the License for the specific language governing permissions and #
\r
13 # limitations under the License. #
\r
14 ##############################################################################*/
\r
17 package org.oran.otf.common.utility.gson;
\r
19 import com.google.gson.Gson;
\r
20 import com.google.gson.GsonBuilder;
\r
21 import com.google.gson.JsonDeserializationContext;
\r
22 import com.google.gson.JsonDeserializer;
\r
23 import com.google.gson.JsonElement;
\r
24 import com.google.gson.JsonParseException;
\r
25 import com.google.gson.JsonPrimitive;
\r
26 import com.google.gson.JsonSerializationContext;
\r
27 import com.google.gson.JsonSerializer;
\r
28 import com.google.gson.reflect.TypeToken;
\r
29 import java.lang.reflect.Type;
\r
30 import java.util.HashMap;
\r
31 import java.util.Map;
\r
32 import org.bson.types.ObjectId;
\r
34 public class GsonUtils {
\r
35 private static final GsonBuilder gsonBuilder =
\r
36 new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
\r
37 .registerTypeAdapter(ObjectId.class, new JsonSerializer<ObjectId>() {
\r
39 public JsonElement serialize(ObjectId src, Type typeOfSrc,
\r
40 JsonSerializationContext context) {
\r
41 return new JsonPrimitive(src.toHexString());
\r
43 }).registerTypeAdapter(ObjectId.class, new JsonDeserializer<ObjectId>() {
\r
45 public ObjectId deserialize(JsonElement json, Type typeOfT,
\r
46 JsonDeserializationContext context) throws JsonParseException {
\r
47 return new ObjectId(json.getAsString());
\r
51 public static Gson getGson() {
\r
52 return gsonBuilder.create();
\r
55 private static final Gson gson = getGson();
\r
56 private static final Type TT_mapStringString = new TypeToken<Map<String,String>>(){}.getType();
\r
58 public static Map<String, String> jsonToMapStringString(String json) {
\r
59 Map<String, String> ret = new HashMap<String, String>();
\r
60 if (json == null || json.isEmpty())
\r
62 return gson.fromJson(json, TT_mapStringString);
\r
64 public static String mapStringObjectToJson(Map<String, Object> map) {
\r
66 map = new HashMap<String, Object>();
\r
67 return gson.toJson(map);
\r