I have different types of fields for an object which is stored as JSONB in the Database Table. I can load the whole table into an Object and need to convert them to POJO Objects.
My JSON to POJO method is
public static <T> T fromJson(String json, Class<T> clazz) {
try {
return OBJECT_MAPPER.readValue(json, clazz);
} catch (JsonProcessingException ex) {
throw new BadJsonException(ex);
}
}
Since I need to pass in the class, I am trying to write an elegant maintainable way to do this. So, if I need to compare two values this works
public static Integer compareFieldValue(
String valueA,
String valueB,
ProjectFieldType fieldType
) {
FieldValue objA;
FieldValue objB;
switch (fieldType) {
case CURRENCY:
objA = JsonHelper.fromJson(valueA, CurrencyField.class);
objB = JsonHelper.fromJson(valueB, CurrencyField.class);
break;
case DATETIME:
objA = JsonHelper.fromJson(valueA, DateTimeField.class);
objB = JsonHelper.fromJson(valueB, DateTimeField.class);
break;
But a long Switch Case Statement doesn't look good. I am trying to have it in an Enum and return it but then I am getting Incompatible Types error
ProjectFieldType.java:[25,44] incompatible types: java.lang.Class<com.foo.model.projectfield.DateTimeField> cannot be converted to java.lang.Class<com.foo.model.projectfield.FieldValue>
In the enum the field class is defined as
private final Class<FieldValue> fieldClazz;
Every Enum value would have a Field Type associated with it. DateTimeField implements FieldValue interface.
Not sure how to go about it. Java is not my first Language, Python is. So, its kinda confusing to me to figure out best ways to do these kinda things in Java World.
Thanks for the help -Shaurya