My goal is to convert a JSON string field to the right class using Jackson.
I have the following class:
public class AnimalRecord {
private String id;
private String source;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "source", include = JsonTypeInfo.As.EXTERNAL_PROPERTY)
@JsonSubTypes(value = {
@JsonSubTypes.Type(value = CatProbeMetadata.class, name
= "catProbeMetadata"),
@JsonSubTypes.Type(value = DogProbeMetadata.class, name = "dogProbeMetadata"),
})
private AnimalMetadata metadata;
In addition to this class, I have a DB table where I store records of AnimalRecord (AnimalRecord = row). The AnimalMetadata is a different JSON string based on the source of this class. Each source has it's own metadata and class definition. In this example, CatProbeMetadata class will be the output when doing de-serialization from the string when the source is "cat".
The issue is that I'm not sure what to do when reading the rows from the DB. I have the following method:
private class ActiveProbeWrapper implements RowMapper<ActiveProbeRecord> {
@Override
public ActiveProbeRecord mapRow(ResultSet rs, int rowNum) throws SQLException {
String id= rs.getString("id");
String source= rs.getString("source");
Animalmetadata metadata = // NOT SURE WHAT TO DO HERE;
ActiveProbeRecord record = new ActiveProbeRecord(deviceId,segment, source, metadata);
return record;
}
}
I need to convert the string in the DB to the right class instance, but my metadata string will NOT include the source (since it's outside the metadata JSON).
The question: Will I have to add the "source" field to the metadata itself or is there any better way of doing this that I missed?
Updated example: Example of DB rows: id | source | metadata 1 | catSource | {"catName": "Mewy"} 2 | dogSource | {"dogName": "Barky"}
When I read the rows from the DB I want to use the source field to de-serialize metadata to the right class - String --> CatMetadata