@JsonCreator and mixin via Module not working for

2019-02-19 23:06发布

问题:

I am trying to deserialize java.net.HttpCookie which doesn't have a default no-arg constructor and am getting: org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class java.net.HttpCookie]: can not instantiate from JSON object (need to add/enable type information?) at [Source: java.io.StringReader@5a395674; line: 1, column: 35

This is with jackson-mapper-asl v 1.9.13

I found Jackson 3rd Party Class With No Default Constructor and attempted to use their solution via both getDeserializationConfig and using module. I present the module code below.

abstract class HttpCookieMixIn {
    @JsonCreator
    public HttpCookieMixIn(@JsonProperty("name") String name, @JsonProperty("value") String value) {
        logger.info("Mixin called!");
    }
}

public class MyModule extends SimpleModule {
    public MyModule() {
        super("ModuleName", new Version(0,0,1,null));
    }

    @Override
    public void setupModule(SetupContext context) {
        context.setMixInAnnotations(java.net.HttpCookie.class, HttpCookieMixIn.class);
        logger.info("Set mixin annotation");
    }
}

In the server endpoint's constructor I have the following:

public ServerEndpointConstructor() {
    mapper = new ObjectMapper();
    mapper.registerModule(new MyModule());
}

I see "Set mixin annotation" is logged prior to the deserialization exception in my logs. I do not see "Mixin called!" ever (though I'm not sure the code inside the mixin constructor would be called). Can someone please show me the error in my ways? Do I need to annotate all the fields inside of java.net.HttpCookie?

http://docs.oracle.com/javase/7/docs/api/java/net/HttpCookie.html

回答1:

I solved this issue, the problem was that I had defined the mixin as a non-static inner class inside of the class in which it was used. Moving it and the module to their own class definitions in their own package fixed this. One could alternatively mark the mixin inner classes as "static" to fix the issue.

Credit to Jackson Mixin not working for deserializing non-default constructor object wherein the author made a comment on the necessity of this while posting his own question.