001// --------------------------------------------------------------------------------
002// Copyright 2002-2024 Echo Three, LLC
003//
004// Licensed under the Apache License, Version 2.0 (the "License");
005// you may not use this file except in compliance with the License.
006// You may obtain a copy of the License at
007//
008//     http://www.apache.org/licenses/LICENSE-2.0
009//
010// Unless required by applicable law or agreed to in writing, software
011// distributed under the License is distributed on an "AS IS" BASIS,
012// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013// See the License for the specific language governing permissions and
014// limitations under the License.
015// --------------------------------------------------------------------------------
016
017package com.echothree.util.common.string;
018
019import com.google.gson.Gson;
020import com.google.gson.GsonBuilder;
021import com.google.gson.reflect.TypeToken;
022import java.util.Collections;
023import java.util.Map;
024
025public class GraphQlUtils {
026    
027    private GraphQlUtils() {
028        super();
029    }
030    
031    private static class GraphQlUtilsHolder {
032        static GraphQlUtils instance = new GraphQlUtils();
033    }
034    
035    public static GraphQlUtils getInstance() {
036        return GraphQlUtilsHolder.instance;
037    }
038
039    private static final Gson GSON = new GsonBuilder()
040            .serializeNulls()
041            .create();
042
043    public String toJson(Map<String, Object> map)  {        
044        return GSON.toJson(map);
045    }
046    
047    public Map<String, Object> toMap(String json) {
048        var typeToken = new TypeToken<Map<String, Object>>() {
049        };
050        
051        Map<String, Object> map = GSON.fromJson(json, typeToken.getType());
052        
053        return map == null ? Collections.emptyMap() : map;
054    }
055    
056}