将字段传递给自定义反序列化器类Jackson [英] Pass a field to custom deserializer class Jackson
问题描述
我编写了一个自定义反序列化程序,只使用jackson映射必需的字段。开始。
I have written a custom deserializer to map only the required fields using jackson. Here goes.
public class GeneralDeserializer extends JsonDeserializer<GeneralDomain> {
@Override
public GeneralDomain deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
final JsonNode jsonNode = jp.getCodec().readTree(jp);
final Map<String, String> map = new ObjectMapper().convertValue(jsonNode, Map.class);
final String event = "Proxy";
return new GeneralDomain(map.get("id"), event, map.get("name"), map.get("lastLogin"));
}
@Override
public Class<GeneralDomain> handledType() {
return GeneralDomain.class;
}
}
我也有一个mixin类,为此添加额外的注释。
I have a mixin class too for this to add extra annotations.
@JsonDeserialize(using = GeneralDeserializer.class)
public class GeneralDomainMixIn{}
我以这种方式获取对象,
I fetch the object in this way,
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(GeneralDomain.class, SimpleRevealPublicEventMixIn.class);
String json = "{\"id\": 111, \"name\": David, \"lastLogin\": \"02-10-2016 10:32:00 AM\"}";
GeneralDomain readValue = mapper.readValue(json, GeneralDomain.class);
这很好用。但正如您在自定义反序列化器中看到的那样,我很难对事件字段值进行编码。这将由主类中的其他实例变量传递。我必须将此字段传递给自定义反序列化器。那么有没有办法在反序列化器中访问这个变量?或者还有其他替代方法来实现这一目标吗?请帮帮我。谢谢。
This works great. But as you can see in the custom deserializer, I am hard coding the event field value. This will be passed on by some other instance variable in the main class. I have to pass this field to the custom deserializer. So is there a way to access this variable inside the deserializer? Or is there any other alternative way to achieve this? Please help me out. Thanks.
推荐答案
最后得到答案。感谢Philip在这个链接。
Got the answer finally. Thanks to Philip in this link.
我所要做的就是这个。
创建一个InjectableValues实例
Create an instance of InjectableValues
private InjectableValues newInjectableValues() {
return new InjectableValues.Std()
.addValue("event", "proxy")
}
使用此方法在mapper类中设置injectablevalues方法
use this method to set the injectablevalues method in mapper class
GeneralDomain readValue = mapper.setInjectableValues(injectEventType()).readValue(json, GeneralDomain.class);
在我的deserialize方法中,我必须检索InjectableValues提供的值:
In my deserialize method I had to retrieve the values provided by the InjectableValues:
String event = String.valueOf(ctxt.findInjectableValue("event", null, null));
这篇关于将字段传递给自定义反序列化器类Jackson的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!