CustomDeserializer has no default (no arg) constructor

后端 未结 2 2190
無奈伤痛
無奈伤痛 2020-12-14 21:23

I am consuming a REST Api with RestTemplate. The response I\'m getting from the API has lots of nested objects. Here\'s a little snippet as an example:

\"for         


        
相关标签:
2条回答
  • 2020-12-14 21:39

    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.

    0 讨论(0)
  • 2020-12-14 21:43

    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);
       }
       ...
    }
    
    0 讨论(0)
提交回复
热议问题