package com.m2pool.common.core.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @ClassName JsonUtil
 * @Description JSON 转换工具类
 * @Author yyb
 * @Date 2025/4/10 16:08
 */
public class JsonUtil {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将 JSON 字符串转换为指定类型的对象
     * @param jsonString JSON 字符串
     * @param clazz 目标对象的类类型
     * @param <T> 目标对象的类型
     * @return 转换后的对象
     * @throws RuntimeException 如果转换失败
     */
    public static <T> T convertString2Object(String jsonString, Class<T> clazz) {
        try {
            return objectMapper.readValue(jsonString, clazz);
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert JSON string to object", e);
        }
    }

    /**
     * 将对象转换为 JSON 字符串
     * @param object 要转换的对象
     * @return JSON 字符串
     * @throws RuntimeException 如果转换失败
     */
    public static String toJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert object to JSON string", e);
        }
    }
}
