如何使用<String>杰克逊 JSON 将 JSON 字符串转换为 Map<String, Set>



我知道通过以下方式将 JSON 字符串转换为Map<String, String>的实现:

public <T1, T2> HashMap<T1, T2> getMapFromJson(String json, Class<T1> keyClazz, Class<T2> valueClazz) throws TMMIDConversionException {
    if (StringUtils.isEmpty(json)) {
        return null;
    }
    try {
        ObjectMapper mapper = getObjectMapper();
        HashMap<T1, T2> map = mapper.readValue(json, TypeFactory.defaultInstance().constructMapType(HashMap.class, keyClazz, valueClazz));
        return map;
    } catch (Exception e) {
        Logger.error(e.getMessage(), e.getCause());
    }
} 

但是我无法扩展它以将我的 JSON 转换为Map<String, Set<String>>.显然,上述方法失败了,因为它破坏了 Set 项并放入列表中。在这里需要一些帮助!!谢谢

示例 JSON 字符串如下所示。此 JSOn 必须转换为 Map<String, Set<CustomClass>>

{
    "0": [
        {
            "cid": 100,
            "itemId": 0,
            "position": 0
        }
    ],
    "1": [
        {
            "cid": 100,
            "itemId": 1,
            "position": 0
        }
    ],
    "7": [
        {
            "cid": 100,
            "itemId": 7,
            "position": -1
        },
        {
            "cid": 140625,
            "itemId": 7,
            "position": 1
        }
    ],
    "8": [
        {
            "cid": 100,
            "itemId": 8,
            "position": 0
        }
    ],
    "9": [
        {
            "cid": 100,
            "itemId": 9,
            "position": 0
        }
    ]
}

试试这个:

JavaType setType = mapper.getTypeFactory().constructCollectionType(Set.class, CustomClass.class);
JavaType stringType = mapper.getTypeFactory().constructType(String.class);
JavaType mapType = mapper.getTypeFactory().constructMapType(Map.class, stringType, setType);
String outputJson = mapper.readValue(json, mapType)

不幸的是,Class真的不能表达泛型类型;所以如果你的值类型是泛型的(如Set<String>),你需要传递JavaType。这也可用于构建结构化JavaType实例。

最新更新