猿问

Java POJO 属性映射

我有一个用例,我在这样的请求中收到一些属性,


"filters": [

  {

    "field": "fName",

    "value": "Tom"

  },

  {

    "field": "LName",

    "value": "Hanks"

  }

]

我没有为此定义的模型。我只是在请求中收到这些属性,并使用这些属性触发对弹性搜索的查询。我在弹性搜索中的记录具有相同的属性名称。


现在,我必须支持一个属性名称完全不同的遗留应用程序。例如:fName变成firstName并且lName变成lastName。


问题:需要在请求中接受旧的属性名称,将它们转换为新的,以便匹配我的弹性搜索记录。在从应用程序发送响应之前,获取具有新属性名称的数据并转换回旧属性名称。


注意:我没有为这些记录定义 POJO。


如何有效地实现这一目标?我正在考虑使用 Orika 映射器,但不确定在不首先定义类的情况下如何工作。


守着星空守着你
浏览 209回答 3
3回答

达令说

是什么阻止您编写从请求 JSON 到规范化 JSON 的转换器?我能想到的正常流程是:Request JSON -> POJO -> POJO with normalized value -> Normalized JSON所以你的 POJO 看起来像:public class Filter {&nbsp; &nbsp; &nbsp;List<FieldFilter> filters;&nbsp; &nbsp; &nbsp;public static class FieldFilter {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;private String field;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;private String value;&nbsp; &nbsp; &nbsp;}}现在您将拥有一个转换图,如: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然后你转换你的 POJO:Filter filterRequest;List<FieldFilters> normlizedFilters =&nbsp;&nbsp; &nbsp; filterReq.getFilters().stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(f -> new FieldFilter(fieldNameMapping.get(f.getField()), f.getValue())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(toList());然后将 Filter 类转换为规范化的 JSON。

拉莫斯之舞

我们有一个类似的场景,我们使用的是apache JOLT。如果您想尝试一些示例,可以参考jolt-demo-online-utility

守候你守候我

最后,这里不需要中间对象类型。你还说,你还没有这种类型,发明它,只是为了改造它,真的没有意义。
随时随地看视频慕课网APP

相关分类

Java
我要回答