简体   繁体   English

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

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

I'm using Jackson and JsonDeserializer.我正在使用 Jackson 和 JsonDeserializer。 When I deserialize to MyClass, you need to set the MyContext class.当我反序列化为 MyClass 时,需要设置 MyContext class。 I used to use static final constants, but I cannot use that for my reason (I need to use instance constants).我曾经使用 static 最终常量,但由于我的原因我不能使用它(我需要使用实例常量)。 I am doing deserialization using ObjectMapper.我正在使用 ObjectMapper 进行反序列化。

Here is the code I tried.这是我尝试过的代码。

@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);

How can I dynamically set constants during deserialization?如何在反序列化期间动态设置常量?

I am using a translator.我正在使用翻译器。 Thank you.谢谢你。

The problem stands in the fact that you are trying to register your context object in your mapper 's config in the wrong way: you can use the DeserializationConfig withAttribute method that returns a new configuration including your context object and then set your mapper with the new configuration:问题在于您试图以错误的方式在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));

After that the context object is available in the your JsonDeserializer class like you wrote:之后, 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