When it deserializes JSON data, added annotations in the entity class are used. Thus,
name value will be applied as constructor parameters to create a
User object from JSON data.
Suppose you released this app with a version 1.0. Later, you want to show more user information in your app. To support it, the backend now returns more data.
Then, the entity class has an additional constructor parameter with
ObjectMapper uses that key to get the data in the JSON data. Let’s say this is the version 1.1. When you release this change to the market, some users will have a crash issue. Why some users rather than all users?
The crash happens because of
UnrecognizedPropertyException. By default, Jackson generates this exception if there is unknown property. When the v1.0 was released, there was no exception. The issue started when the backend returned more data for v1.1. v1.1 doesn’t have a problem because all properties from the backend JSON data are consumed. However, v1.0 doesn’t know how to handle unrecognized property,
gender. In short, only v1.0 has a crash issue. It is vital to mention that not all users update their app up to date.
Since users have an older version, the only way to fix it is to return the different data considering the app version from the backend. Although this would fix the crash issue, the backend code gets messy due to checking versions.
There is nothing we can do for already happened. However, we can prepare better if we know what could happen. I believe the best approach is to support the forward compatibility by adding
@JsonIgnoreProperties(ignoreUnknown = true) always for the entity class. If the entity class in v1.0 had this annotation, there would have been no exception and no need to change the backend.
Forward compatibility or upward compatibility is a design characteristic that allows a system to accept input intended for a later version of itself. A standard supports forward compatibility if a product that complies with earlier versions can “gracefully” process input designed for later versions of the standard, ignoring new parts which it does not understand.
There is another way to ignore properties. You can set
FAIL_ON_UNKNOWN_PROPERTIESas false. However, the error still could happen. There could be multiple
ObjectMapperand some may not have that configuration. Adding
@JsonIgnorePropertiesis safe since there is always one entity class.
UnrecognizedPropertyException happens because it doesn’t support the forward compatibility by default. This type of error could be hard to know before experiencing. By adding
@JsonIgnoreProperties(ignoreUnknown = true) always in your entity class, your earlier apps can handle the later data gracefully.