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
版权声明:本文标题:java - Configuring list deserialization by element - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738646289a2104606.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论