簡體   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