12

I am aware of the implementation which converts JSON string to a Map<String, String> through :

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>>. The above method fails, obviously, as it breaks the Set items and puts in the list. Need some help here!! Thanks

Sample JSON String is as below. This JSOn has to converted to a 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
        }
    ]
}
3
  • The JSON would help... Commented Dec 17, 2014 at 10:22
  • I have added a sample JSON. Thanks. Commented Dec 17, 2014 at 10:34
  • And how would that map to a Multimap? Commented Dec 17, 2014 at 10:35

2 Answers 2

24

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)
Sign up to request clarification or add additional context in comments.

Comments

1

Unfortunately Class really can not express generic types; so if your value type is generic (like Set<String>), you need to pass JavaType instead. And that can be used to construct structured JavaType instances as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.