Reputation: 1029
I am using a class from another module in my request.
public class KeyInput {
@NotNull
private Long id;
@NotNull
private String startValue;
@NotNull
private String endValue;
}
I cannot put @JsonIgnoreProperties(ignoreUnknown = true)
annotation on this class, since the module does not contain jackson library.
Putting it on field level where I used it on my request class didn't work out.
@JsonIgnoreProperties(ignoreUnknown = true)
private List<KeyInput> keys;
Here is the incoming request. Notice the source of the problem, the two fields (name and type), which are not declared in KeyInput class.
{
"id": 166,
"name": "inceptionDate",
"type": "DATE",
"startValue": "22",
"endValue": "24"
}
How am I supposed to tell the jackson to ignore the unknown fields if the class is not in my package?
P.S: I know I can get the keys as json string and serialize it using ObjectMapper (by setting the configuration DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
to false), but I am looking for a cleaner solution here.
Also putting those fields in my class and never use it, is another dirty solution.
Upvotes: 4
Views: 1247
Reputation: 1690
Two ways come to my mind.
Create an empty child class that inherit from KeyInput
class. This is the easiest method.
@JsonIgnoreProperties(ignoreUnknown = true)
public class InheritedKeyInput extends KeyInput{}
Create a custom de-serializer for KeyInput
class.
public class KeyInputDeserializer extends JsonDeserializer<KeyInput> {
@Override
public KeyInput deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
KeyInput keyInput = new KeyInput();
keyInput.setId(node.get("id").asLong());
keyInput.setEndValue(node.get("startValue").textValue());
keyInput.setStartValue(node.get("startValue").textValue());
return keyInput;
}
}
Bind this de-serializer to KeyInput
using a configuration class
@Configuration
public class JacksonConfig implements Jackson2ObjectMapperBuilderCustomizer {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
builder.failOnEmptyBeans(false)
.deserializerByType(KeyInput.class, new KeyInputDeserializer());
}
}
Upvotes: 2
Reputation: 481
just simple add on above filed which you wanna ignore @JsonIgnore
Upvotes: 0