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

Passing String value to Jackson Custom Deserializer in Java

我创建了一个 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 {

我想将 "String argument" 传递给我想在反序列化过程中使用的反序列化方法。有办法吗?

我在我的代码中调用解串器如下:

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

测试 Class 是:

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

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

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.

另外,看看:

  • How to inject dependency into Jackson Custom deserializer