Home > Software engineering >  How to add a constant* during JSON deserialization using Jackson
How to add a constant* during JSON deserialization using Jackson

Time:01-23

I'm using Jackson and JsonDeserializer. When I deserialize to MyClass, you need to set the MyContext class. I used to use static final constants, but I cannot use that for my reason (I need to use instance constants). I am doing deserialization using 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.

CodePudding user response:

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:

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:

MyContext myContext = (MyContext) deserializationContext.getConfig()
                                 .getAttributes()
                                 .getAttribute("context");
  •  Tags:  
  • Related