package com.chushang.common.core.jackson;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

@Slf4j
public class JacksonUtils {

    private static final ObjectMapper mapper = new ObjectMapper();

    @SneakyThrows
    public static String toJSONString(Object data) {
        if (null == data) {
            return "";
        }
        return mapper.writeValueAsString(data);
    }

    @SneakyThrows
    public static <T> T json2Bean(String jsonData, Class<T> beanType) {
        if (null == jsonData) {
            return null;
        }
        return mapper.readValue(jsonData, beanType);
    }

    @SneakyThrows
    public static <T> List<T> json2List(String jsonData, Class<T> beanType) {
        if (null == jsonData) {
            return List.of();
        }
        JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, beanType);
        return mapper.readValue(jsonData, javaType);
    }

    @SneakyThrows
    public static <K, V> Map<K, V> json2Map(String jsonData, Class<K> keyType, Class<V> valueType) {
        if (null == jsonData) {
            return Map.of();
        }
        JavaType javaType = mapper.getTypeFactory().constructMapType(Map.class, keyType, valueType);
        return mapper.readValue(jsonData, javaType);
    }
}
