Java POJO attributes mapping

User0911 :

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.

Mạnh Quyết Nguyễn :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35910&siteId=1