We’re using Java POJOs as messages that flow through a message broker. They are serialized/deserialized using the Jackson JSON library. Each message (POJO) can have multiple versions:
class UserCreatedV1 { private String email; private String fullName; }
class UserCreatedV2 { private String email; private String fullName; private String preferredName; }
(getters, constructors, etc are omitted). What is the way to:
- ensure no errors happen during deserialization, even when a client that uses
UserCreatedV1
deserializes a json representation ofUserCreatedV2
(or vice-versa) - statically check if
UserCreatedV2
is backward/forward compatible withUserCreatedV1
(no need to enforce this though)
2
Answers
You can mark your POJO with
@JsonIgnoreProperties(ignoreUnknown = true)
so this way when deserializing into POJO v1 the fields that are exclusive to v2 will be ignored, and when deserialising into v2 from JSON v1 missing properties will be set to null. You can read about ignoring unknown properties here: Jackson Unmarshalling JSON with Unknown PropertiesYou can use the Jackson library’s polymorphic deserialization feature.
Here is an example of how you can use polymorphic deserialization in Jackson to support multiple versions of the UserCreated message:
Next, define the concrete classes:
When you deserialize a JSON payload, Jackson will automatically determine the version based on the value of the "version" property, and deserialize the payload into the appropriate class.