package com.mes.device.util; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; /** * 工具类:解析 DeviceConfig.configJson 的多种格式 * 兼容对象结构和 [{paramKey,paramValue}] 数组结构 */ @Slf4j public final class ConfigJsonHelper { private static final TypeReference> MAP_TYPE = new TypeReference>() {}; private static final TypeReference>> LIST_TYPE = new TypeReference>>() {}; private ConfigJsonHelper() { } /** * 将 configJson 解析为 key-value 的 Map * * @param configJson 原始 JSON 字符串 * @param objectMapper 公共 ObjectMapper * @return 参数映射,不可修改 */ public static Map parseToMap(String configJson, ObjectMapper objectMapper) { if (configJson == null || configJson.trim().isEmpty()) { return Collections.emptyMap(); } String trimmed = configJson.trim(); try { if (trimmed.startsWith("[")) { List> items = objectMapper.readValue(trimmed, LIST_TYPE); Map result = new LinkedHashMap<>(); for (Map item : items) { if (item == null) { continue; } Object keyObj = firstNonNull(item.get("paramKey"), item.get("key")); if (keyObj == null) { continue; } Object valueObj = firstNonNull(item.get("paramValue"), item.get("value")); result.put(String.valueOf(keyObj), valueObj); } return result; } else if (trimmed.startsWith("{")) { return objectMapper.readValue(trimmed, MAP_TYPE); } else { log.warn("未知的 configJson 格式: {}", trimmed); } } catch (Exception e) { log.warn("解析 configJson 失败: {}", trimmed, e); } return Collections.emptyMap(); } private static Object firstNonNull(Object first, Object second) { return Objects.nonNull(first) ? first : second; } }