Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson error : no suitable constructor for a simple class

Tags:

java

json

jackson

I am in trouble, here is a class I want to Serialize/Deserialize with Jackson 2.3.2. The serialization works fine but not the deserialization.

I have this exception as below:

No suitable constructor found for type [simple type, class Series]: can not instantiate from JSON object (need to add/enable type information?)

The weirdest thing is that it works perfectly if I comment the constructor!

public class Series {

private int init;
private String key;
private String color;

public Series(String key, String color, int init) {
    this.key = key;
    this.init = init;
    this.color = color;
}

//Getters-Setters

}

And my unit test :

public class SeriesMapperTest {

private String json = "{\"init\":1,\"key\":\"min\",\"color\":\"767\"}";
private ObjectMapper mapper = new ObjectMapper();

@Test
public void deserialize() {
    try {
        Series series = mapper.readValue(json, Series.class);
    } catch (IOException e) {
        Assert.fail(e.getMessage());
    }
}
}

This exception is throwing from the method deserializeFromObjectUsingNonDefault() of BeanDeserializerBase of Jackson lib.

Any idea?

Thanks

like image 563
Julien Deruere Avatar asked Aug 03 '14 04:08

Julien Deruere


1 Answers

Jackson does not impose the requirement for classes to have a default constructor. You can annotate the exiting constructor with the @JsonCreator annotation and bind the constructor parameters to the properties using the @JsonProperty annotation. Note: @JsonCreator can be even suppressed if you have single constructor.

This approach has an advantage of creating truly immutable objects which is a good thing for various good reasons.

Here is an example:

public class JacksonImmutable {
    public static class Series {

        private final int init;
        private final String key;
        private final String color;

        public Series(@JsonProperty("key") String key,
                      @JsonProperty("color") String color,
                      @JsonProperty("init") int init) {
            this.key = key;
            this.init = init;
            this.color = color;
        }

        @Override
        public String toString() {
            return "Series{" +
                    "init=" + init +
                    ", key='" + key + '\'' +
                    ", color='" + color + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        String json = "{\"init\":1,\"key\":\"min\",\"color\":\"767\"}";
        System.out.println(mapper.readValue(json, Series.class));
    }
}
like image 159
Alexey Gavrilov Avatar answered Sep 20 '22 14:09

Alexey Gavrilov