[英]Jackson - how to write custom deserializer
我想使用Jackson类将我的HashMaps列表转换为对象列表(我已经读过可以完成)。
我要序列化的对象如下所示:
public class FinancialTransaction {
private Date tranDate;
private String tranDescription;
private Double debit;
private Double credit;
...getters and setters...
我想做这样的事情...
ArrayList<FinancialTransaction> transactions =
new ArrayList<FinancialTransaction>();
HashMap<String, String> records = new HashMap<String, String>();
records.put("tranDate", "08/08/2014");
records.put("tranDescription", "08/08/2014");
records.put("debit", "1.50");
records.put("credit", null);true);
for (HashMap<String, String> record : records) {
ObjectMapper m = new ObjectMapper();
FinancialTransaction ft = m.convertValue(record, FinancialTransaction.class);
transactions.add(ft);
}
return transactions;
HashMap的键值等于我的FinancialTransaction类中的属性的名称,但这些值都是字符串。
因为哈希图的所有值都是字符串,所以在尝试从映射转换为对象时遇到错误。 这使我认为我需要编写自定义解串器? 有人可以帮我定制的反序列化器类的外观如何。 或者,如果我不需要,那会更好。
谢谢
您无需编写自定义序列化程序。 只要地图条目类型与类字段的类型相对应,Jackson就可以从地图转换为您的类型。
这是一个例子:
public class JacksonConversion {
public static class FinancialTransaction {
public Date tranDate;
public String tranDescription;
public Double debit;
public Double credit;
@Override
public String toString() {
return "FinancialTransaction{" +
"tranDate=" + tranDate +
", tranDescription='" + tranDescription + '\'' +
", debit=" + debit +
", credit=" + credit +
'}';
}
}
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map1 = new HashMap<>();
map1.put("tranDate", new Date().getTime());
map1.put("tranDescription", "descr");
map1.put("debit", 123.45);
Map<String, Object> map2 = new HashMap<>();
map2.put("tranDate", new Date().getTime());
map2.put("tranDescription", "descr2");
map2.put("credit", 678.9);
System.out.println(mapper.convertValue(
Arrays.asList(map1, map2),
new TypeReference<List<FinancialTransaction>>() {}));
}
}
输出:
[FinancialTransaction{tranDate=Fri Aug 08 12:24:51 CEST 2014, tranDescription='descr', debit=123.45, credit=null}, FinancialTransaction{tranDate=Fri Aug 08 12:24:51 CEST 2014, tranDescription='descr2', debit=null, credit=678.9}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.