Jackson Mixin not working for deserializing non-de

2019-07-22 08:22发布

This question already has an answer here:

I am writing a mixin to deserialize a string into javax.servlet.http.Cookie

Mixin.java

package a;
import org.codehaus.jackson.annotate.JsonProperty;

public abstract class MixIn {
      MixIn(@JsonProperty("name") String name, @JsonProperty("value") String value) { }

}

HelloWorld.java

package b;

import a.MixIn;

ObjectMapper mapper = new ObjectMapper();
mapper.getDeserializationConfig().addMixInAnnotations(Cookie.class, MixIn.class);
Cookie aCookie = mapper.readValue("{"name":"abc","value":"xyz"}", Cookie.class);

It seems to provide "JsonMappingException: No suitable constructor found for type [simple type, class javax.servlet.http.Cookie]" error.

Please do note that

- Mixin is (has to be) defined as a separate class (NOT an inner class, not static)

- Mixin and the class where its used are (have to be) in 2 different packages.

I am using jackson 1.9.9

2条回答
三岁会撩人
2楼-- · 2019-07-22 08:42

Don't you need to include @JsonCreator over the mixin constructor? I'm still struggling with a similar issue myself, so I'm not 100% certain here.

My question: @JsonCreator and mixin via Module not working for 3rd Party Class

Update: my example in the above question is working, your comment on the mixin needing to be in a separate package and not an inner class did the trick, thanks!

查看更多
甜甜的少女心
3楼-- · 2019-07-22 08:46

Creating a separate class for the Mixin,

public abstract class MixinClass extends OriginalClass {

    //`datamember` is the datamember required to create instance of OriginalClass
    @JsonCreator
    MixinClass(@JsonProperty("item") datamember item) { super(item); }
}

In the mapper class add this,

objectMapper.addMixInAnnotations(OriginalClass.class, MixinClass.class);

This will resolve the issue. Make sure that the MixinClass is a separate .java file and not an inner class.

查看更多
登录 后发表回答