package shop.alien.second.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 从JSON字符串中获取指定key的值
     */
    public static String getJsonValue(String jsonString, String key) {
        try {
            JsonNode jsonNode = objectMapper.readTree(jsonString);
            JsonNode valueNode = jsonNode.get(key);
            return valueNode != null ? valueNode.asText() : null;
        } catch (Exception e) {
            throw new RuntimeException("解析JSON失败", e);
        }
    }

    /**
     * 获取指定key的值（支持各种数据类型）
     */
    public static <T> T getJsonValue(String jsonString, String key, Class<T> valueType) {
        try {
            JsonNode jsonNode = objectMapper.readTree(jsonString);
            JsonNode valueNode = jsonNode.get(key);
            return objectMapper.treeToValue(valueNode, valueType);
        } catch (Exception e) {
            throw new RuntimeException("解析JSON失败", e);
        }
    }
}
