Jackson 1.8.0 ObjectMapper to serialize/deserializ

2019-07-29 12:42发布

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

Consider the following example:

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

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

objectMapper.canDeserialize(type)

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

Thanks for your help!

2条回答
做个烂人
2楼-- · 2019-07-29 12:50

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) {...}
}

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.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-07-29 13:11

Yes it can serialize POJOs without custom serializer. But the problem in your case is that all your properties are "hidden". By default, Jackson will look for:

  • Public fields and getters (getXxx())
  • Setters (setXxx()) of any visibility

To make Jackson use private fields you can annotate them with @JsonProperty, or change default visibility check levels, if you want all private (or protected, package visible) fields to be found. This can be done by annotation (@JsonAutoDetect), or by defining global visibility checker.

查看更多
登录 后发表回答