问题
Problem definition:
There is a Java server which stores JSON
data that can be mapped to a Java Class. The Java Class is subject to changes. The goal is to be able to update the Java Class and still be able to decode the JSON
data of an older version to a Java Object of a newer version. There should be a good versioning system in place. For example the ability to add a new field to the Java Class with a default value. In the case the old JSON
data doesn't have this field, the Java object can use the default value of the field.
Questions:
- I've seen
GSON
, but the versioning support is too limited.
Did I miss something? Are there other libraries that have a better versioning support?
- How should one store that
JSON
data?
I see two options. Option 1: I can store those JSON
files (which have a common structure if they have the same version) separately in a folder. For example I have 2 files: json/j1.json and json/j2.json. Option 2: I can use a NoSQL
Database such as MongoDB
. But Does this have an advantage over the previous option? It is pointless to ask for a BasicDBObject
in a DBCollection
since I need it to be able to cast it to another Java Class. Which option is recommended for this case? Maybe another option is better suited?
回答1:
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. See the module's GitHub page for examples of the full functionality.
Disclaimer: I am the author of this module. I have also written a Spring MVC ResponseBodyAdvise for using the module.
来源:https://stackoverflow.com/questions/18447117/json-data-storage-with-versioning