package com.gxwebsoft.common.core.utils;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.util.TimeZone;

/**
 * JSON解析工具类
 *
 * @author WebSoft
 * @since 2017-06-10 10:10:39
 */
public class JSONUtil {
    /**
     * 注意：不要直接 new ObjectMapper() 否则不支持 Java8 时间类型（LocalDateTime 等）。
     * 这里做最小可用配置，避免在 Redis/日志/签名等场景序列化失败。
     */
    private static final ObjectMapper objectMapper;
    private static final ObjectWriter objectWriter;

    static {
        objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        objectWriter = objectMapper.writerWithDefaultPrettyPrinter();
    }

    /**
     * 对象转json字符串
     *
     * @param value 对象
     * @return String
     */
    public static String toJSONString(Object value) {
        return toJSONString(value, false);
    }

    /**
     * 对象转json字符串
     *
     * @param value  对象
     * @param pretty 是否格式化输出
     * @return String
     */
    public static String toJSONString(Object value, boolean pretty) {
        if (value != null) {
            if (value instanceof String) {
                return (String) value;
            }
            try {
                if (pretty) {
                    return objectWriter.writeValueAsString(value);
                }
                return objectMapper.writeValueAsString(value);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * json字符串转对象
     *
     * @param json  String
     * @param clazz Class
     * @return T
     */
    public static <T> T parseObject(String json, Class<T> clazz) {
        if (StrUtil.isNotBlank(json) && clazz != null) {
            try {
                return objectMapper.readValue(json, clazz);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
