3

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

Yasin Okumuş
  • 2,299
  • 7
  • 31
  • 62
Darshan
  • 116
  • 1
  • 1
  • 8
  • 1
    I'm still not able to reproduce. Here is the link to my code: https://github.com/Alexey1Gavrilov/stackoverflow/tree/master/src/main/java/stackoverflow/mixin – Alexey Gavrilov Jul 17 '14 at 17:03
  • Marked as a duplicate of a more recent question. The answer to both is in THIS question. – Dave May 24 '19 at 01:10

2 Answers2

8

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.

Nikhil Katre
  • 2,114
  • 23
  • 22
1

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!

Community
  • 1
  • 1
Matt P.
  • 193
  • 3
  • 9