[英]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.