package cn.sikey.websocket.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.experimental.UtilityClass;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

/**
 * @Author: nelson
 * @Date: 2025/5/29
 * @Description: ObjectMapperUtil
 */
@UtilityClass
public class ObjectMapperUtil {
    private final static ObjectMapper objectMapper;

    static {
        objectMapper = new Jackson2ObjectMapperBuilder()
                .createXmlMapper(false)
                .failOnEmptyBeans(false)
                .failOnUnknownProperties(false)
                .build();
//        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
        objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
    }

    public <T> T convertValue(Object fromValue, Class<T> toValueType) {
        return objectMapper.convertValue(fromValue, toValueType);
    }

    public String writeValueAsString(Object value) throws Exception {
        return objectMapper.writeValueAsString(value);
    }

    public <T> T convertValue(Object fromValue, TypeReference<T> toValueTypeRef) {
        return objectMapper.convertValue(fromValue, toValueTypeRef);
    }

    public <T> TypeReference<T> getValueTypeRef() {
        return new TypeReference<>() {
        };
    }
}
