package com.tzld.longarticle.recommend.server.util;

import com.alibaba.fastjson.JSONObject;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

@Slf4j
public class JSONUtils {


    public static String toJsonNew(Object obj) {
        if (obj == null) {
            return "";
        }
        try {
            return JSONObject.toJSONString(obj);
        } catch (Exception e) {
            log.error("toJson exception", e);
            return "";
        }
    }
    public static String toJson(Object obj) {
        if (obj == null) {
            return "";
        }
        try {
            return new Gson().toJson(obj);
        } catch (Exception e) {
            log.error("toJson exception", e);
            return "";
        }
    }

    public static <T> T fromJson(String value, TypeToken<T> typeToken, T defaultValue) {

        if (StringUtils.isBlank(value)) {
            return defaultValue;
        }
        try {
            return JSONObject.parseObject(value, typeToken.getType());
        } catch (Exception e) {
            log.error("parseObject error! value=[{}]", value, e);
        }
        return defaultValue;
    }

}
