How to know what all properties are ignored by @JsonIgnoreProperties(ignoreUnknown=true)

孤街醉人 提交于 2021-02-11 02:00:21

问题


I need to serialize - deserialized an existing Java POJO in my code. The POJO is big + it has few parent classes in the hierarchy. The code is using spring and so Jackson internally. I started fixing one by one issue I found by fixing getter-setter name, including @JsonIgnore etc and after considerable time I fixed it completely.

But I have to fix several such classes, so for the next class, I just added: @JsonIgnoreProperties(ignoreUnknown=true) which worked but during the testing I found it ignored a property it should not ignore. The property was like

@JsonIgnoreProperties(ignoreUnknown=true)
class MyClass {
   private String xyz;
   public String getXyzValue() {
     return this.xyz;
   }
   public void setXyz(String xyz) {
     this.xyz = xyz;
   }
}

So basically I had to correct the getter method here.

Question: Is there a way to use @JsonIgnoreProperties(ignoreUnknown=true) but list down all ignored properties for further analysis?


回答1:


Remove JsonIgnoreProperties annotation and register your own com.fasterxml.jackson.databind.deser.DeserializationProblemHandler problem handler. See below example:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler;
import com.fasterxml.jackson.databind.json.JsonMapper;

import java.io.IOException;

public class JsonApp {

    public static void main(String[] args) throws IOException {
        String json = "{\"xyz\":\"X\",\"a\":1,\"yxz\":2}";
        DeserializationProblemHandler handler = new DeserializationProblemHandler() {
            @Override
            public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser p, JsonDeserializer<?> deserializer, Object beanOrClass, String propertyName) throws IOException {
                System.out.println("Unknown property '" + propertyName + "' for " + beanOrClass.getClass());
                return true;
            }
        };
        JsonMapper mapper = JsonMapper.builder()
                .addHandler(handler)
                .build();

        mapper.readValue(json, MyClass.class);
    }
}

Above code prints:

Unknown property 'a' for class com.example.MyClass
Unknown property 'yxz' for class com.example.MyClass

Note

JsonMapper class is introduced in version 2.10. Below this version you can use ObjectMapper constructor.



来源:https://stackoverflow.com/questions/59831961/how-to-know-what-all-properties-are-ignored-by-jsonignorepropertiesignoreunkno

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!