2

I'm using Jackson 2.6.3 to deserialize JSON strings to Java objects and I have a piece of code below:

ObjectMapper objectMapper = new ObjectMapper();
HashMap<?, ?> result = objectMapper.readValue("null", HashMap.class);
// result is null 
System.out.println(result == null);

I wonder if Jackson has any configurations to not convert String "null" to null object but throw an exception?

toandv
  • 982
  • 13
  • 25

1 Answers1

0

I don't know Jackson very well but what about a simple method, maybe in your UtilClass, like this:

public <T> T deserialize(final ObjectMapper objectMapper, final String jsonString, final Class<T> yourClass) throws Exception 
{
   if(jsonString == null || jsonString.equalsIgnoreCase("null"))
      throw new Exception(); //maybe change the type's exception
   return objectMapper.readValue(jsonString, yourClass);
}
Gianni B.
  • 2,691
  • 18
  • 31
  • Yes, it's simple, but if you are deserializing from a byte array, you have to do a little bit more to pre-check the input. It's not so convenient. – toandv Jan 14 '16 at 09:43