du369
du369

Reputation: 821

How to deserialize different versions of the same bean class while the field structure of the bean class periodically changes?

For example, I had a stable server running. It registered the server status on a zookeeper instance by serializing a Status instance in json format.

Some time later, I added a instance field to the Status class and started another testserver regitsering its server status on the same zookeeper instance.

Now I need to write some inspector program to monitor both servers. What should I do so that it deserializes both versions properly and hopefully handles future versions of Status class?

I tried to remove all fields and use a map instead. But it doesn't feel very convenient. Like this:

public class Status
{
    private int serverId;
    //...
}

// changes to
public class Status
{
    public static final String SERVERID = "serverId";

    private Map<String, Object> properties = new HashMap<>();
    //... 
}

Any suggestions? Is there any best practice dealing with such situation?

Upvotes: 1

Views: 88

Answers (1)

Anthony BONNIER
Anthony BONNIER

Reputation: 355

If you use Jackson to serialize and deserialize your classes, you can set configurations to ignore unknown or missing fields to allow the evolution of your Status bean :

  • FAIL_ON_UNKNOWN_PROPERTIES
  • FAIL_ON_MISSING_CREATOR_PROPERTIES

This will allow the monitor to work with different versions of server Status JSON instances.

Upvotes: 1

Related Questions