huang
2025-11-18 1566e4c7604d85737ea67fe6757e71b8185fa48e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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<String, Object>> MAP_TYPE =
            new TypeReference<Map<String, Object>>() {};
    private static final TypeReference<List<Map<String, Object>>> LIST_TYPE =
            new TypeReference<List<Map<String, Object>>>() {};
 
    private ConfigJsonHelper() {
    }
 
    /**
     * 将 configJson 解析为 key-value 的 Map
     *
     * @param configJson   原始 JSON 字符串
     * @param objectMapper 公共 ObjectMapper
     * @return 参数映射,不可修改
     */
    public static Map<String, Object> parseToMap(String configJson, ObjectMapper objectMapper) {
        if (configJson == null || configJson.trim().isEmpty()) {
            return Collections.emptyMap();
        }
        String trimmed = configJson.trim();
        try {
            if (trimmed.startsWith("[")) {
                List<Map<String, Object>> items = objectMapper.readValue(trimmed, LIST_TYPE);
                Map<String, Object> result = new LinkedHashMap<>();
                for (Map<String, Object> 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;
    }
}