All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cz.mmsparams.api.json.JsonUtilsSafe Maven / Gradle / Ivy

The newest version!
package cz.mmsparams.api.json;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.io.Reader;

import cz.mmsparams.api.logging.APILoggerFactory;
import cz.mmsparams.api.logging.ApiLogFacade;
import cz.mmsparams.api.logging.ILogger;
import cz.mmsparams.api.utils.ByteUtil;
import cz.mmsparams.api.utils.StringUtil;


public class JsonUtilsSafe
{
    public static final String TAG = JsonUtilsSafe.class.getSimpleName();
    private static final ILogger LOGGER = APILoggerFactory.getLogger(JsonUtilsSafe.class);

    private JsonUtilsSafe()
    {
    }

    public static String getPretty(final String json)
    {
        JsonParser parser = new JsonParser();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        JsonElement el = parser.parse(json);
        return gson.toJson(el); // done
    }


    public static  T fromJson(byte[] serialized, Class clazz)
    {
        try
        {
            if (ByteUtil.isEmptyOrNull(serialized))
                return null;

            return fromJson(new String(serialized), clazz);
        }
        catch (Exception e)
        {
            ApiLogFacade.logEx(LOGGER, "fromJson: " + serialized + " : " + clazz, e);
            return null;
        }
    }

    public static  T fromJson(String serialized, Class clazz)
    {
        try
        {
            if (StringUtil.isEmptyOrNull(serialized))
                return null;

            return JsonUtils.fromJson(serialized, clazz);
        }
        catch (Exception e)
        {
            ApiLogFacade.logEx(LOGGER, "fromJson: " + serialized + " : " + clazz, e);
            return null;
        }
    }

    public static  T fromJson(Reader serialized, Class clazz)
    {
        try
        {
            return JsonUtils.fromJson(serialized, clazz);
        }
        catch (Exception e)
        {
            ApiLogFacade.logEx(LOGGER, "fromJson: " + serialized + " : " + clazz, e);
            return null;
        }
    }

    public static String toJson(Object object)
    {
        try
        {
            if (object == null)
                return null;
            return JsonUtils.toJson(object);
        }
        catch (Exception e)
        {
            ApiLogFacade.logEx(LOGGER, "fromJson: " + object, e);
            return null;
        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy