Saving a Java Object into database as JSON
There are some ways to save a object (e.g. Java object) into database. One of the ways is to serialize a object and store it into a text column.
We can serialize a object by implementing serializable interface in Java. But it is difficult to parse the serialised data by using other programming languages and it's not human-readable. To avoid this difficulty, we can use JSON format as serialised data format.
Unlike serializable interface, JSON does not have official versioning method. When you add a new field in the Java object, data in the database are still stored as JSON without the new filed. When you deserialize data without new field by using a serialization/deserialization library (such as Jackson), the library may throw an exception. For example, Jackson throws UnrecognizedPropertyException. We can avoid the exception when we have a setting to ignore unknown fields. In Jackson, you do it by using annotation or object mapper configuration.
- annotation
@JsonIgnoreProperties(ignoreUnknown = true) public class YourClass { }
- object mapper configuration
ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);