杰克逊 - 如何编写自定义反序列化器

时间:2014-08-08 08:08:30

标签: java jackson

我想使用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类中属性的名称,但值都是字符串。

因为hashmap的所有值都是字符串,所以在尝试从地图转换为我的对象时会出错。这让我觉得我需要编写自定义反序列化器?有人可以帮助我解决我的自定义反序列化程序应该如何看待。或者如果我不需要更好的那个。

感谢

1 个答案:

答案 0 :(得分:1)

您无需编写自定义序列化程序。只要地图条目类型与类字段的类型相对应,杰克逊就可以从地图转换为您的类型。

以下是一个例子:

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}]