1 回答

TA貢獻1799條經(jīng)驗 獲得超9個贊
您需要創(chuàng)建帶有額外參數(shù)的構造函數(shù),該參數(shù)將在反序列化期間使用:
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 + '\'' +
'}';
}
}
上面的代碼打?。?/p>
{"value":"Value"}
Test{value='Extra value!!!'}
您應該始終提供給super constructor您POJO class的Test.class. 如果您需要更復雜的初始化,請查看ContextualDeserializer.
添加回答
舉報