0

I am trying to implement an endpoint which takes a List<SomeClass> via @RequestBody and supports partial processing / fault tolerancy.

As in, even if some elements are wrong (may even be different type, but still valid JSON), discard them and continue with the next one instead of throwing an exception and failing fast.

I am already calling the validator programmatically on each element instead of utilizing @Valid, but whenever I receive something with different schema or type, I get a com.fasterxml.jackson.databind.exc.MismatchedInputException.

How can I change this behavior to not fail but ignore and process the next element instead?

I am using Spring Boot 2.2.3.RELEASE.

I tried using @JsonIgnoreProperties(ignoreUnknown = true), but when I receive non-object types, the exception is still thrown.

Example JSON I'd like to process:

[
    null,
    [],
    {},
    -1,
    false,
    "Test",
    { "someKey": "someValue" }
]

Where only { "someKey": "someValue" } is a valid SomeClass definition.

Aron
  • 55
  • 1
  • 7
  • 1
    Define 'completely wrong'. For example, if your thing expects a JSON array, and the input breaks JSON spec, should this be allowed? – BeUndead Jan 22 '20 at 16:49
  • Could you please post your code related to this issue? then we might help you. – Jonathan JOhx Jan 22 '20 at 16:50
  • you can use the jackson @JsonIgnoreProperties(ignoreUnknown = true) at class level to ignore unknown fields. – dassum Jan 22 '20 at 16:52

1 Answers1

1

I'd create a custom deserializer for Spring:

How to provide a custom deserializer with Jackson and Spring Boot

Then, in my deserializer, I'd process the JSON string to a generic JSON array and loop through it trying to deserialize each item in the array.

For successful ones, add them to the list that your deserializer will return. For ones that do not "work", throw them away and continue processing.

Without code, there's not much else to help with.

mikeb
  • 10,578
  • 7
  • 62
  • 120
  • Thanks, that is a good approach. My only issue is that by creating a custom deserializer, I lose the ability to deserialize valid cases out-of-the-box and I have to reimplement the parsing by hand. There is probably a workaround for that, I am off to do some experiments with this. – Aron Jan 22 '20 at 19:12
  • No, your first attempt in your custom deserializer should be to do the whole thing in one whack and get exactly what you want. If that fails fall back to one-by-one – mikeb Jan 22 '20 at 19:38