[英]What is the elegant way to parse a map into an object?
I have a random object and I need to parse Map<String, String>我有一个随机的 object,我需要解析 Map<String, String>
public class ExternalIncome {
private Long operationId;
private OffsetDateTime operationDate;
private String operationCode;
private String documentNumber;
private OffsetDateTime documentDate;
private String correspondentInn;
private String correspondentName;
private String correspondentAccount;
}
I've just created it this way, but I think it's not quite elegant, rather ugly.我只是这样创建的,但我认为它不是很优雅,而且很丑陋。 Also, I need to intercept every iterate of the parsing to hold dynamic fields into Map<String, String> inside of the object.此外,我需要拦截解析的每个迭代,以将动态字段保存到 object 内部的 Map<String, String> 中。
public static ExternalIncome create(Map<String, String> fields) {
ExternalIncome externalIncome = new ExternalIncome();
fields.forEach((k, v) -> {
switch (k) {
case "OPER_ID":
externalIncome.setOperationId(nullableLong(v));
break;
case "OPER_DATE":
externalIncome.setOperationDate(Utils.toOffsetDateTime(v));
break;
etc
Could you help me to find the best way?你能帮我找到最好的方法吗?
You can do it using Jackson's ObjectMapper class, if you are allowed to use third part library.如果允许使用第三方库,则可以使用 Jackson 的 ObjectMapper class 来完成。
final ObjectMapper mapper = new ObjectMapper();
final ExternalIncome income = mapper.convertValue(fields,ExternalIncome.class)
I don't see any elegant solution in your case, but you get rid of switch/case by using map where the key is the field name from the fields map and value is BiDirectionalConsumer.在你的案例中我没有看到任何优雅的解决方案,但是你通过使用 map 摆脱了 switch/case,其中键是字段 map 中的字段名称,值是 BiDirectionalConsumer。 Probably not the best solution, but still.可能不是最好的解决方案,但仍然如此。 Note: be careful with casts and type conversions.注意:小心强制转换和类型转换。
Let's say you have fields map:假设您有字段 map:
Map<String, String> fields = new HashMap<>();
fields.put("OPER_ID", "3");
You can define the second map with field names and operation you want to perform:您可以使用要执行的字段名称和操作来定义第二个 map:
HashMap<String, BiConsumer<ExternalIncome, Object>> fieldsOperations = new HashMap<>();
fieldsOperations.put("OPER_ID", (extIncome, valueToSet) ->
extIncome.setOperationId(Long.valueOf((String) valueToSet))); //add as many as you want
And then where you iterate over your map with fields:然后你在哪里迭代你的 map 字段:
ExternalIncome externalIncome = new ExternalIncome();
fields.forEach((k,v) -> {
BiConsumer<ExternalIncome, Object> operation = fieldsOperations.get(k);
if (operation == null) {
//add to dynamic fields map
return;
}
operation.accept(externalIncome, v);
});
Or you can reconsider your data structure to get rid of the idea to have dynamic fields, but idk if it's possible with your use case.或者您可以重新考虑您的数据结构以摆脱拥有动态字段的想法,但如果您的用例可能的话,请考虑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.