如何使用Jackson JSON将JSON字符串转换为Map<String,Set<String>>?

11

我了解将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
        }
    ]
}

JSON可以帮助... - Boris the Spider
我已经添加了一个示例JSON。谢谢。 - Nihal Sharma
那句话怎么映射到“Multimap”呢? - Boris the Spider
2个回答

21

试一下这个:

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)

1

很不幸,Class 确实无法表示通用类型;因此,如果您的值类型是通用的(例如 Set<String>),则需要传递 JavaType。这可以用于构造结构化的 JavaType 实例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接