将字符串值传递给Java中的Jackson自定义反序列化器

时间:2019-03-06 16:57:12

标签: java json jackson jackson2

我创建了一个Jackson自定义反序列化器以反序列化JSON字符串:

public class TestMapper extends StdDeserializer<Test> {

    public TestMapper() {
        this(null);
    }

    public TestMapper(Class<?> vc) {
        super(vc);
    }

    @Override
    public Test deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {

我想向反序列化过程中要使用的反序列化方法传递“字符串参数”。有办法吗?

我在代码中按如下方式调用反序列化器:

new ObjectMapper().readValue(json, Test.class)

,测试类为:

@JsonDeserialize(using = TestMapper.class)
public class Test {

1 个答案:

答案 0 :(得分:1)

您需要创建一个构造函数,该构造函数将使用您的额外参数,该参数将在反序列化期间使用:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.io.IOException;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        SimpleModule customModule = new SimpleModule();
        customModule.addDeserializer(Test.class, new TestMapper("Extra value!!!"));

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

        Test test = new Test();
        test.setValue("Value");

        String json = mapper.writeValueAsString(test);
        System.out.println(json);
        System.out.println(mapper.readValue(json, Test.class));
    }
}

class TestMapper extends StdDeserializer<Test> {

    private String extraConfig;

    public TestMapper() {
        this(null);
    }

    public TestMapper(String extraConfig) {
        super(Test.class);
        this.extraConfig = extraConfig;
    }

    @Override
    public Test deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        Test test = new Test();
        test.setValue(extraConfig);

        return test;
    }
}

class Test {

    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Test{" +
                "value='" + value + '\'' +
                '}';
    }
}

上面的代码显示:

{"value":"Value"}
Test{value='Extra value!!!'}

您应始终向super constructor提供您的POJO class,例如Test.class。如果您需要更复杂的初始化,请查看ContextualDeserializer

另外,看看: