简体   繁体   中英

Spring Boot @RestController, be tolerant to MismatchedInputException when deserializing a Collection in @RequestBody

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM