gpt4 book ai didi

java - 有没有办法在不破坏反序列化过程的情况下忽略 JsonProcessingException

转载 作者:太空宇宙 更新时间:2023-11-04 10:20:59 24 4
gpt4 key购买 nike

我正在研究一种将 Jackson 反序列化 JSON 到类实例的解决方案,而不破坏整个过程,目前当我执行以下操作时:

如果 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
}

并反序列化 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);

或者直接作为 Play 框架:

final Character character = Json.fromJson(json, Character.class);

我肯定会遇到这样的异常:

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

InvalidFormatException实际上是一个JsonProcessingException,还有MismatchedInputException和其他异常,所以我需要以某种方式优雅地继续处理并获取对象charact并至少具有name值而不是完全停止它。

我更喜欢:

  • 使用注释来配置解析器或任何要应用于 BaseDTO 的解决方案。
  • 将问题记录在日志文件中,以便我知道发生了错误。

如果不付出巨大的努力,我现在真的找不到方法,所以我想知道是否有任何开箱即用的解决方案可以做到这一点,而无需重新发明轮子。

最佳答案

我假设您希望将像 N/A 这样的字符串视为 null。使用自定义解串器可以这样实现。

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()));
}
}

希望这有帮助!

关于java - 有没有办法在不破坏反序列化过程的情况下忽略 JsonProcessingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51173480/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com