小编典典

让Jackson在所有地方都使用自定义解串器(对于不是我的类型)

java

我正在尝试设置Jackson
JSON自定义解串器,以将JSON值转换为Long对象。我按照此站点上的说明进行操作:http
:
//wiki.fasterxml.com/JacksonHowToCustomDeserializers来设置自定义解串器。

但是,为了使自定义解串器生效,我必须每次都添加注释,例如

public class TestBean {
    Long value;

    @JsonDeserialize(using=LongJsonDeserializer.class)
    public void setValue(Long value) {
       this.value = value;
     }
 }

有没有办法告诉Jackson始终使用自定义反序列化器对所有Long属性进行反序列化,而不必@JsonDeserialize(using=LongJsonDeserializer.class)每次都使用注释?


阅读 208

收藏
2020-09-18

共1个答案

小编典典

LongJsonDeserializer deserializer = new LongJsonDeserializer();

SimpleModule module =
  new SimpleModule("LongDeserializerModule",
      new Version(1, 0, 0, null, null, null));
module.addDeserializer(Long.class, deserializer);

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);

这是完整的演示应用程序。这适用于杰克逊的最新版本,可能还适用于杰克逊版本回到1.7。

import java.io.IOException;

import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.module.SimpleModule;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    TestBean bean = new TestBean();
    bean.value = 42L;

    ObjectMapper mapper = new ObjectMapper();

    String beanJson = mapper.writeValueAsString(bean);
    System.out.println(beanJson);
    // output: {"value":42}

    TestBean beanCopy1 = mapper.readValue(beanJson, TestBean.class);
    System.out.println(beanCopy1.value);
    // output: 42

    SimpleModule module =
      new SimpleModule("LongDeserializerModule",
          new Version(1, 0, 0, null));
    module.addDeserializer(Long.class, new LongJsonDeserializer());

    mapper = new ObjectMapper();
    mapper.registerModule(module);

    TestBean beanCopy2 = mapper.readValue(beanJson, TestBean.class);
    System.out.println(beanCopy2.value);
    // output: 126
  }
}

class TestBean
{
  Long value;
  public Long getValue() {return value;}
  public void setValue(Long value) {this.value = value;}
}

class LongJsonDeserializer extends JsonDeserializer<Long>
{
  @Override
  public Long deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException
  {
    Long value = jp.getLongValue();
    return value * 3;
  }
}
2020-09-18