skip to Main Content

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 of UserCreatedV2 (or vice-versa)
  • statically check if UserCreatedV2 is backward/forward compatible with UserCreatedV1 (no need to enforce this though)

2

Answers


  1. 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 Properties

    Login or Signup to reply.
  2. You 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:

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "version")
    @JsonSubTypes({
        @JsonSubTypes.Type(value = UserCreatedV1.class, name = "v1"),
        @JsonSubTypes.Type(value = UserCreatedV2.class, name = "v2")
    })
    public abstract class UserCreated {
        private String email;
        private String fullName;
    
        // getters/setters
    }
    

    Next, define the concrete classes:

    public class UserCreatedV1 extends UserCreated {
        // no additional fields
    }
    
    public class UserCreatedV2 extends UserCreated {
        private String preferredName;
    
        // getters/setters
    }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search