admin管理员组

文章数量:1203386

There is a need to deserialize the list of objects piecemeal. How can this be done?

Example:

I have response: [{"keyFirst": "value", "keySecond": ["some-value"]}], where SomeClass.class:

String keyFirst;
List<String> keySecond;

But suddenly, instead of List, I receive a Map in the response via restclient. The entire list broken when deserialized. How can I set up item-by-element deserialization to weed out broken objects and output the log?

I tried to do this through a custom deserializer with its registration in ObjectMapper.

@Slf4j
public class SafeSomeClassListDeserializer extends JsonDeserializer<List<SomeClass>> {

    @Override
    public List<SomeClass> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        List<SomeClass> result = new ArrayList<>();

        ArrayNode arrayNode = p.getCodec().readTree(p);

        for (JsonNode node : arrayNode) {
            try {
                SomeClass myObject = p.getCodec().treeToValue(node, SomeClass.class);
                result.add(myObject);
            } catch (Exception ex) {
                log.error("Error deserialization object: {}; Message: ", node, ex);
            }
        }

        return result;
    }
}

and

@Bean
    public JsonTemplateToObjectMapper getMapper() {
        SimpleModule module = new SimpleModule();
        module.addDeserializer(List.class, new SafeSomeClassListDeserializer());

        return new JsonTemplateToObjectMapper(
                new ObjectMapper()
                        .enable(ALLOW_SINGLE_QUOTES)
                        .disable(WRITE_DATES_AS_TIMESTAMPS)
                        .disable(FAIL_ON_UNKNOWN_PROPERTIES)
                           .enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
                        .setVisibility(FIELD, ANY)
                        .setSerializationInclusion(JsonInclude.Include.NON_NULL)
                        .registerModules(new JavaTimeModule(), module)
        );
    }

where JsonTemplateToObjectMapper is the mapper from the library through which I receive data from the service.

Maybe someone has experience with a similar task? Thanks!

本文标签: javaConfiguring list deserialization by elementStack Overflow