package org.jeecg.module.custom.ocr.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import java.util.Map;
import java.util.HashMap;

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

    public static Map<String, String> jsonToMap(String jsonString) {
        try {
            // 先将JSON字符串转换为Map<String, Object>
            Map<String, Object> originalMap = objectMapper.readValue(
                    jsonString,
                    new TypeReference<Map<String, Object>>() {}
            );

            // 转换为Map<String, String>
            Map<String, String> resultMap = new HashMap<>();
            for (Map.Entry<String, Object> entry : originalMap.entrySet()) {
                Object value = entry.getValue();
                // 处理不同类型的值
                if (value == null) {
                    resultMap.put(entry.getKey(), null);
                } else if (value instanceof String ||
                        value instanceof Number ||
                        value instanceof Boolean) {
                    resultMap.put(entry.getKey(), value.toString());
                } else {
                    // 对于复杂对象（Map、List等），转换为JSON字符串
                    resultMap.put(entry.getKey(), objectMapper.writeValueAsString(value));
                }
            }
            return resultMap;
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert JSON to Map", e);
        }
    }
}
