0

I have the below function for deserialization. I am passing an object to obj field. If one of the value in object is empty string it gives me a null pointer exception. How can I avoid this situation?

public static MultiValueMap convertFilterToMultiValueMap(ObjectMapper objectMapper, Object obj) {
        MultiValueMap parameters = new LinkedMultiValueMap();
        Map<String, Object> map = (Map)objectMapper.convertValue(obj, new TypeReference<Map<String, Object>>() {
        });
        map.forEach((key, value) -> {
            if (value instanceof List) {
                ((List)value).forEach((item) -> {
                    map.put(key, item.toString());
                });
            } else {
                map.put(key, value.toString());
            }

        });
        parameters.setAll(map);
        return parameters;
    }
Anamika
  • 11
  • 4
  • If value is null, then `value.toString()` will fail. Either don't put it in the map if it is null, or put `"null"` (the string) into the map instead (`Objects.toString` might help). But it all depends on your requirements. This question has nothing to do with deserialization, but is a classical NPE question. – knittl Jan 25 '23 at 06:58
  • I think you should not pass null obj to the method convertFilterToMultiValueMap(ObjectMapper objectMapper, Object obj). Maybe you can check obj != null before the method call? – Wing Kui Tsoi Jan 25 '23 at 07:14

0 Answers0