简体   繁体   English

如何将JSON字符串转换为Map <String, Set<String> &gt;杰克逊JSON

[英]How to convert a JSON string to a Map<String, Set<String>> with Jackson JSON

I am aware of the implementation which converts JSON string to a Map<String, String> through : 我知道通过以下方式将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());
    }
} 

But I cannot extend it to convert my JSON to a Map<String, Set<String>> . 但是我无法扩展它以将我的JSON转换为Map<String, Set<String>> The above method fails, obviously, as it breaks the Set items and puts in the list. 显然,上面的方法失败了,因为它打破了Set项并放入列表中。 Need some help here!! 需要一些帮助!! Thanks 谢谢

Sample JSON String is as below. 示例JSON字符串如下所示。 This JSOn has to converted to a Map<String, Set<CustomClass>> . 此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
        }
    ]
}

Try this: 尝试这个:

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)

Unfortunately Class really can not express generic types; 不幸的是Class真的无法表达泛型类型; so if your value type is generic (like Set<String> ), you need to pass JavaType instead. 因此,如果您的值类型是通用的(如Set<String> ),则需要传递JavaType And that can be used to construct structured JavaType instances as well. 这也可以用于构造结构化JavaType实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM