CustomDeserializer has no default (no arg) constructor

吃可爱长大的小学妹 提交于 2019-12-03 12:12:34

It is required that you have a default constructor without arguments. What you can do is create one (or replace the other one if you don't really need it):

public class CustomDeserializer extends StdDeserializer<Efs> {

   public CustomDeserializer() {
       super(Efs.class);
   }
   ...
}

There is also one trap that users can fall into (like my self). If you declare deserializer as a inner class (not a static nested class) like:

@JsonDeserialize(using = DomainObjectDeserializer.class)
public class DomainObject {
    private String key;

    public class DomainObjectDeserializer extends StdDeserializer<DomainObject> {
        public DomainObjectDeserializer() {
            super(DomainObject.class);
        }

        @Override
        public DomainObject deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            // code
        }
    }
}

Jackson uses the Class#getDeclaredConstructor() with no argument (method accepts vararg) witch means: give me a default (no argument) constructor. Code above will throw exception when Jackson tries to create DomainObjectDeserializer because javac does generate the constructor that does accept enclosing class reference. Technically speaking DomainObjectDeserializer does not have a default constructor.

For a curiosity sake you can execute DomainObjectDeserializer.class.getDeclaredConstructors() and ensure that method does return single element array containing constructor definition with enclosing class reference.

The DomainObjectDeserializer should be declared as a static class.

Here is a good answer to read in more details.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!