I have a use case where I receive some attributes in the request like this,
"filters": [
{
"field": "fName",
"value": "Tom"
},
{
"field": "LName",
"value": "Hanks"
}
]
I don't have a model defined for this. I just receive these attributes in the request and fire a query on elastic search using these attributes. My records in elastic search have the same attribute names.
Now, I have to support a legacy application where attribute's names are completely different. E.g.: fName becomes firstName and lName becomes lastName.
Problem: Need to accept old attribute names in the request, convert them to new ones so that it matches my elastic search records. Fetch the data with new attribute names and convert back to old ones before sending out the response from the application.
NOTE: I don't have POJO's defined for these records.
How can this be achieved effectively? I was thinking of using Orika mapper but not sure how that will work without defining classes first.
A quick look at how to convert a POJO from/to a Map<K, V> with Jackson: // Create ObjectMapper instance ObjectMapper mapper = new ObjectMapper(); // Converting POJO to Map Map<String, Object> map = mapper. convertValue(foo, new TypeReference<Map<String, Object>>() {}); // Convert Map to POJO Foo anotherFoo = mapper.
POJOs are intended to contain business logic, according to Martin Fowler, who invented the term.
You can attach an annotation to a public class field or a public getter or setter method. Every bound class requires at least an @Id annotation to define the object property that holds the object id. A bound POJO class must contain exactly one @Id annotation.
What prevents you from writing a transformer from request JSON to your normalized JSON?
The normal flow I can think of is:
Request JSON -> POJO -> POJO with normalized value -> Normalized JSON
So your POJO looks like:
public class Filter {
List<FieldFilter> filters;
public static class FieldFilter {
private String field;
private String value;
}
}
Now you will have a transformation map like:
Map<String, String> fieldNameMapping = new HashMap<>();
fieldNameMapping.put("fName", "firstName");
fieldNameMapping.put("firstName", "firstName");
// The process of populating this map can be done either by a static initializer, or config/properties reader
Then you transform your POJO:
Filter filterRequest;
List<FieldFilters> normlizedFilters =
filterReq.getFilters().stream()
.map(f -> new FieldFilter(fieldNameMapping.get(f.getField()), f.getValue())
.collect(toList());
Then convert the Filter class to your normalized JSON.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With