Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is JsonDeserializer#deserialize(...) allowed to return null?

Tags:

jackson

A Web service returns "location" objects with properties that map almost 1:1 to the fields of android.location.Address. I've written a custom deserializer to handle them, and it works.

Occasionally the Web service returns garbage locations, i.e., latitude 0.0, longitude 0.0, other fields empty strings. I'd like these garbage locations to be deserialized as a Java null.

Is JsonDeserializer#deserialize(...) allowed to return null?

I haven't simply tested this myself because:

  • The behavior of a particular version of Jackson is not a guarantee unless it's documented.
  • It's quicker to write this question than mock the bogus input or write a separate test app.
  • The answer might be beneficial to others.
like image 725
Kevin Krumwiede Avatar asked Jan 30 '26 02:01

Kevin Krumwiede


1 Answers

JsonDeserializer#deserialize is allowed to return null by the design of JsonDeserializer class, although it is not explicitly mentioned in the Javadoc of the method.

This can be assumed by the existence, default implementation and documentation of methods JsonDeserializer#getNullValue and JsonDeserializer#getEmptyValue.

These methods can be called to produce return values for deserialize e.g.

return getNullValue();

when the JsonToken is null or empty respectively. By default they return null and that will be returned by deserialize.

See here an example with getNullValue.

like image 147
Manos Nikolaidis Avatar answered Feb 02 '26 15:02

Manos Nikolaidis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!