简体   繁体   中英

Jackson objectMapper readValue on String of JSON Array - ignore errors

I have a JSON array with some objects which are not of my class methods and I want to ignore them / catch them, this is how my JSON look:

[{
  "id": 1,
  "name": "John"
}, {
   "badItem": true
}]

and I'm running the code to convert the above string to my class (with id and name fields), like this:

List<Person> personList = new ArrayList<>();
        try {
            personList = objectMapper.readValue(msg, new TypeReference<List<Person>>() {});
        } catch (Exception e) {
            logger.error("De-Serialization failed", e);
            response.addErrorMsg(e.toString());
        }

All my read will fail because of one bad item. How I can catch only the bad items and parse only the objects from the list that can work? (eg John and catch badItem)

According to: https://www.baeldung.com/jackson-deserialize-json-unknown-properties
You can configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

I assume it will create empty objects for "bad items" that you might need to filter out later..

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