I have a class where I had a String
field but now I changed it to List<String>
public TestClass{
// String field; was
List<String> field; // now
}
But the problem is that I already have some data in database. I was saving this class as json into db, and when I need to retrieve it I was parcing it. But now it fails with error because it can't parse single String (how it was before) into List<String>
(how it's now). Can I somehow change this behaviour?
Right now I'm parsing it like that:
public <T> T parse(String s, Class<T> clazz) { // clazz is TestClass.class, String is json from DB
try {
return objectMapper.readValue(s, clazz); // objectMapper is ObjectMapper
} catch (JsonProcessingException e) {
...
}
}
But obviously I will have both types of fields in my DB (old ones and new ones), can I somehow parse just a string into list but it should also work for list into list too?
CodePudding user response:
The correct way to fix the problem when you modify a data model is to create an SQL script to transform all existed values in the database into new model.
I know that supporting two versions of the same field is very bad practise. Imaging a bit further. What would you do next time, when you change this field e.g. int a Map<String, Integer>
?!
P.S. In case you still want to go your way, then you have to create your custom deserializer. See ths topic: Baeldung - Deserialization in Jackson
CodePudding user response:
Easiest way is probably to annotate the field field
in the TestClass
with an annotation like:
public TestClass{
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
List<String> field;
}
Alternatively, if adding the annotation to the field is not feasible, you can enable it on the object mapper instead with:
objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)