Jackson 1.8.0 ObjectMapper用于序列化/反序列化任意类 [英] Jackson 1.8.0 ObjectMapper to serialize/deserialize arbitrary classes

查看:1167
本文介绍了Jackson 1.8.0 ObjectMapper用于序列化/反序列化任意类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何告诉Jacksons ObjectMapper序列化我自己的类?我是否必须提供序列化程序?

How can I tell Jacksons ObjectMapper to serialize my own classes? Do I have to provide a serializer?

请考虑以下示例:

public class MyType {
    private int a;
    private String b;
    // Getters and Setters
}

// TODO: configure ObjectMapper, such that the following is true:

objectMapper.canDeserialize(type)

我相信杰克逊有办法自动完成所有工作,而不指定反序列化策略作为MyType的序列化已经有效。

I believe there is a way that Jackson does everything automatically, without specifying a deserialization "strategy" as the serialization of MyType already works.

感谢您的帮助!

推荐答案

我的自定义类有问题,因为它有不明确的setter方法。如果你使用@JsonSetter注释要用作setter的方法的onoe,一切都是正确的。

I had a problem with my custom class, because it had ambigous setter methods. If you annotate onoe of the methods you want to use as setter with @JsonSetter everything is right.

public class MyType {
    private int a;

    @JsonSetter
    public void setA(int a) {...}

    public void setA(String a) {...}
}

没有注释 objectMapper.deserialize(...)失败。在内部会抛出一个提供更多信息的exeption,但它会被捕获并且只返回false。

Without the annotation the objectMapper.deserialize(...) fails. Internally an exeption is thrown that gives you more information, but its caught and only false is returned.

这篇关于Jackson 1.8.0 ObjectMapper用于序列化/反序列化任意类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆