package com.yuchen.saas.park.service.pull.untils;

import com.google.gson.Gson;
import com.yuchen.saas.park.service.pull.exception.DataErrorException;
import org.nest.springwrap.core.tool.api.DeviceCode;

import java.lang.reflect.Type;

/**
 * @author 吕海泉
 * @create 2020/12/21 17:49
 */
public class GsonUtils {
    private static final Gson gson = new Gson();
    public static final String toJson(Object o) {
        return gson.toJson(o);
    }

    public static <T> T fromJson(String json, Class<T> clazz) {
        try {
            return gson.fromJson(json, clazz);
        } catch (Exception e) {
            throw new DataErrorException(DeviceCode.BAD_REQUEST.returnTextCode(), e.getMessage());
        }
    }

    public static <T> T fromJson(String json, Type typeOf) {
        try {
            return gson.fromJson(json, typeOf);
        } catch (Exception e) {
            throw new DataErrorException(DeviceCode.BAD_REQUEST.returnTextCode(), e.getMessage());
        }
    }
}
