问题
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