简体   繁体   English

将字段传递给自定义反序列化器类Jackson

[英]Pass a field to custom deserializer class Jackson

I have written a custom deserializer to map only the required fields using jackson. 我编写了一个自定义反序列化器来使用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;
    }
}

I have a mixin class too for this to add extra annotations. 我也有一个mixin类,可以添加额外的注释。

@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. 谢谢。

Got the answer finally. 终于得到了答案。 Thanks to Philip in this link . 感谢菲利普在这个链接

All I had to do was this. 我所要做的就是这个。

Create an instance of InjectableValues 创建InjectableValues的实例

private InjectableValues injectEventType() {
  return new InjectableValues.Std()
    .addValue("event", "proxy")
}

use this method to set the injectEventType method in mapper class 使用此方法在mapper类中设置injectEventType方法

GeneralDomain readValue = mapper.setInjectableValues(injectEventType()).readValue(json, GeneralDomain.class);

In my deserialize method I had to retrieve the values provided by the InjectableValues: 在我的反序列化方法中,我必须检索InjectableValues提供的值:

String event = String.valueOf(ctxt.findInjectableValue("event", null, null));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM