package com.ruoyi.rocketmq.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

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

    /**
     * 通用JSON解析方法（兼容对象和数组）
     * @param jsonStr JSON字符串
     * @param valueType 目标实体类类型
     * @return 实体类List集合
     */
    public static <T> List<T> parseJsonData(String jsonStr, Class<T> valueType) {
        if (!StringUtils.hasText(jsonStr)) {
            return new ArrayList<>();
        }

        try {
            JsonNode rootNode = objectMapper.readTree(jsonStr);

            if (rootNode.isArray()) {
                // 处理数组格式JSON
                return objectMapper.readValue(jsonStr,
                        objectMapper.getTypeFactory().constructCollectionType(List.class, valueType));
            } else {
                // 处理单个对象格式JSON
                List<T> result = new ArrayList<>(1);
                result.add(objectMapper.readValue(jsonStr, valueType));
                return result;
            }
        } catch (Exception e) {
            throw new RuntimeException("JSON解析失败: " + e.getMessage(), e);
        }
    }
}