繁体   English   中英

如何使用 Jackson 在 JSON 反序列化期间添加常量*

[英]How to add a constant* during JSON deserialization using Jackson

我正在使用 Jackson 和 JsonDeserializer。 当我反序列化为 MyClass 时,需要设置 MyContext class。 我曾经使用 static 最终常量,但由于我的原因我不能使用它(我需要使用实例常量)。 我正在使用 ObjectMapper 进行反序列化。

这是我尝试过的代码。

@JsonDeserialize(using=MyClassDeserializer.class)
class MyClass {
    @JsonIgnore
    private final MyContext context;
    
    public final int foo;
    public final String bar;
}

class MyClassDeserializer extends JsonDeserializer<MyClass> {
    
    @Override
    public PacketContainer deserialize(JsonParser parser, DeserializationContext context)
            throws IOException {
            MyContext myContext = (MyContext) deserializationContext.getConfig().getAttributes().getAttribute("context");
            // It seems no attributes has registered.

            doSome(myContext.foo); // NullPointerException occurs
            // ...
    }
}

class MyContext {
    private String foo;
    private int bar;

    // getter(); setter();
}

// main()
ObjectMapper mapper = new ObjectMapper();
Context context = new Context();
context.setFoo("foo");
context.setBar(0);

HashMap<String, Context> contextSetting = new HashMap<>();
contextSetting.put("context", context);


mapper.getDeserializationConfig().getAttributes().withSharedAttributes(contextSetting);
mapper.getDeserializationContext().setAttribute("context", context);

如何在反序列化期间动态设置常量?

我正在使用翻译器。 谢谢你。

问题在于您试图以错误的方式在mapper的配置中注册context object :您可以使用DeserializationConfig withAttribute方法返回一个新配置,包括您的context object ,然后使用新的配置:

MyContext myContext = new MyContext();
myContext.setFoo("foo");
myContext.setBar(0);

ObjectMapper mapper = new ObjectMapper();
mapper.setConfig(mapper.getDeserializationConfig()
      .withAttribute("context", myContext));

之后, context object 在您的JsonDeserializer class 中可用,就像您写的那样:

MyContext myContext = (MyContext) deserializationContext.getConfig()
                                 .getAttributes()
                                 .getAttribute("context");

暂无
暂无

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

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