[英]Is there any way to ignore JsonProcessingException without breaking deserialization process
I'm looking into a solution for Jackson deserialization JSON to an instance of a class without breaking the whole process, currently when I do something like: 我正在寻找一种针对Jackson的反序列化JSON到类实例的解决方案,而不会破坏整个过程,目前我正在执行以下操作:
If Actor.class was like: 如果Actor.class像这样:
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonPropertyOrder(alphabetic = true)
public abstract class BaseDTO {
}
public class Character extend BaseDTO {
private LocalDateTime updatedDate;
private String name;
// Setters and getters
}
and deserialize json {"updatedDate":"N/A", "name": "Jon Snow"}
like: 并反序列化json {"updatedDate":"N/A", "name": "Jon Snow"}
如下所示:
String json = "{\"updatedDate\":\"N/A\", \"name\": \"Jon Snow\"}";
ObjectMapper mapper = new ObjectMapper();
final Character character = mapper.reader().forType(Character.class).readValue(json);
Or as Play Framework directly: 或直接作为Play框架:
final Character character = Json.fromJson(json, Character.class);
I definitely will get an exception like: 我肯定会得到像这样的异常:
Caused by: com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String "N/A": Text 'N/A' could not be parsed at index 0
And InvalidFormatException
actually is a JsonProcessingException
, there is also MismatchedInputException
and other exceptions, so I need somehow gracefully continue with processing and get the object character
and have name
value at least instead of stopping it at all. InvalidFormatException
实际上是JsonProcessingException
,还有MismatchedInputException
和其他异常,因此我需要以某种方式优雅地继续处理并获取对象character
并至少具有name
值,而不是完全停止它。
I prefer to: 我更喜欢:
BaseDTO
. 使用批注来配置解析器或要应用于BaseDTO
任何解决方案。 I really can't find the way right now without a huge effort, so I wonder if there is any out-of-box solution do that without re-invent the wheel. 我现在真的需要付出巨大的努力才能找到解决之道,所以我想知道是否有任何现成的解决方案可以在不重新发明轮子的情况下做到这一点。
I am assuming that you wannt ot consider string like N/A
as null. 我假设您不希望将N/A
类的字符串视为null。 Using a custom deserializer it can be achieved like this. 使用自定义解串器可以像这样实现。
class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext context) throws IOException {
if ("N/A".equals(p.getText())) return null;
return LocalDateTime.from(DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(p.getText()));
}
}
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.