简体   繁体   中英

Jackson 1.8.0 ObjectMapper to serialize/deserialize arbitrary classes

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM