How to deserialize a class with overloaded constructors using JsonCreator

By | August 7, 2019

Question

I am trying to deserialize an instance of this class using Jackson 1.9.10:

public class Person {

@JsonCreator
public Person(@JsonProperty("name") String name,
        @JsonProperty("age") int age) {
    // ... person with both name and age
}

@JsonCreator
public Person(@JsonProperty("name") String name) {
    // ... person with just a name
}
}

When I try this I get the following

Conflicting property-based creators: already had … {interface org.codehaus.jackson.annotate.JsonCreator @org.codehaus.jackson.annotate.JsonCreator()}], encountered … , annotations: {interface org.codehaus.jackson.annotate.JsonCreator @org.codehaus.jackson.annotate.JsonCreator()}]

Is there a way to deserialize a class with overloaded constructors using Jackson?

Thanks

Solution

Though its not properly documented, you can only have one creator per type. You can have as many constructors as you want in your type, but only one of them should have a @JsonCreator annotation on it.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *