开发者

Upgrade path for json file format

We are storing user preferences for a Java app in a JSON file using Jackson. As we continue to develop the app, we will be adding preferences, renaming preferences, and removing obsolete preferences. When the user upgrades the app to the next version the file format will likely have changed. This causes Jackson to throw an exception and the file can't be parsed even though the format is 90% the same. How should I handle upgrading the file format?

I was thinking about using JSONT to upgrade the file as well as writing my own Jackson stream parser which is more lenient than the full binding parser, just in case something goes wrong with the JSONT upgrade. What have other peo开发者_开发问答ple done to handle upgrading file formats?


Jackson doesn't currently have any built-in JSON versioning support, like Gson does. Jackson issue 108 was logged over two years ago to address such a possible enhancement. Please don't hesitate to vote for its implementation. (I just did.)

The approach I would take would be to implement a custom JSON versioning support solution, similar to how Gson does it. (This one feature alone probably wouldn't be enough for me to switch to Gson.) Then logic in your Java bean processing could be relatively straightforward regarding handling different versions either post-deserialization, or during custom deserialization.


Aside from versioning support (which, like Bruce correctly points out, is one feature that could be added relatively easily), what is usually done is simple allowing unrecognized properties to be ignored, instead of throwing exception.

There are multiple ways to do this (see "How to ignore unknown properties"; simplest one is to just globally change behavior by:

objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Structural changes are more difficult, so it may be good strategy to avoid structural changes other than addition/removal of properties. For example, instead of changing a property from JSON Object to JSON Array (or vice versa), add a new property with new type, deprecate old one.


As @programmer-bruce said, there is no built-in Jackson support at the time of writing this (2.9.x). However, the Jackson Model Versioning Module adds versioning support which can be used to convert old versions of JSON models to the current version (and vice-versa) before being mapped to the POJO.

See my answer on Jackson 2 support for versioning for an example of how GSON's basic versioning functionality can be mapped to this module.

Disclaimer: I am the author of this module. See the GitHub project page for more examples of additional functionality. I have also written a Spring MVC ResponseBodyAdvise for using the module.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜