我正在使用杰克遜和 JsonDeserializer。當我反序列化為 MyClass 時,需要設定 MyContext 類。我曾經使用靜態最終常量,但由于我的原因我不能使用它(我需要使用實體常量)。我正在使用 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);
如何在反序列化期間動態設定常量?
我正在使用一個翻譯系統。謝謝你。
uj5u.com熱心網友回復:
問題在于您試圖以錯誤的方式context在您的配置中注冊您的物件mapper:您可以使用withAttribute方法回傳一個包含您的物件的新配置,然后使用新配置設定您的映射器:DeserializationConfig context
MyContext myContext = new MyContext();
myContext.setFoo("foo");
myContext.setBar(0);
ObjectMapper mapper = new ObjectMapper();
mapper.setConfig(mapper.getDeserializationConfig()
.withAttribute("context", myContext));
之后,就像您寫的那樣,該context物件在您的JsonDeserializer類中可用:
MyContext myContext = (MyContext) deserializationContext.getConfig()
.getAttributes()
.getAttribute("context");
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/418931.html
標籤:
上一篇:使用jq創建JSON
