001// --------------------------------------------------------------------------------
002// Copyright 2002-2026 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 graphql.GraphQLException;
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        Object parsed = GSON.fromJson(json, Object.class);
049        Map<String, Object> result = Collections.emptyMap();
050
051        if(parsed instanceof Map) {
052            result = (Map<String, Object>)parsed;
053        } else if(parsed != null) {
054            throw new GraphQLException("Expected a JSON object or null.");
055        }
056
057        return result;
058    }
059    
060}