Jackson Mixin不用于反序列化非默认构造函数对象 [英] Jackson Mixin not working for deserializing non-default constructor object

查看:149
本文介绍了Jackson Mixin不用于反序列化非默认构造函数对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个mixin来将字符串反序列化为javax.servlet.http.Cookie



Mixin.java

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

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

}

HelloWorld.java



<$ p $包> 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);

它似乎提供了JsonMappingException:没有为类型[simple type,class javax.servlet.http.Cookie]找到合适的构造函数错误。



请注意


- Mixin是(必须)被定义为一个单独的类(不是内在的) class,not static)


- Mixin和它所使用的类(必须是)在2个不同的包中。



我正在使用jackson 1.9.9

解决方案

为Mixin创建一个单独的类,

 公共抽象类MixinClass扩展OriginalClass {

//`datamember`是创建OriginalClass实例所需的数据库
@JsonCreator
MixinClass (@JsonProperty(item)datamember item){super(item); }
}

在mapper类中添加此项,

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

这将解决问题。确保MixinClass是一个单独的.java文件而不是内部类。


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

解决方案

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.

这篇关于Jackson Mixin不用于反序列化非默认构造函数对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆