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.