我有一个类型的对象User(如下定义),它在序列化为 Json 时会引发此特定错误:com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.providenceuniversal.gim.AuthenticationRequest["user"]->com.providenceuniversal.gim.User["lastSeenToLocal"])User定义(具有相关属性和方法):public class User implements ServerMessage { //..... private final @JsonInclude(Include.NON_NULL) Instant lastSeen; @JsonCreator User(@JsonProperty("username") String username) { if (!isValidUsername(username)) throw new IllegalArgumentException("Invalid constructor argument values"); this.username = username.trim(); this.firstName = null; this.lastName = null; this.email = null; this.status = null; this.joinDate = null; this.lastSeen = null; this.dateOfBirth = null; } @JsonCreator User( @JsonProperty("username") String username, @JsonProperty("firstName") String firstName, @JsonProperty("lastName") String lastName, @JsonProperty("email") String email, @JsonProperty("status") String status, @JsonProperty("joinDate") Instant joinDate, @JsonProperty("lastSeen") Instant lastSeen, @JsonProperty("dateOfBirth") LocalDate dateOfBirth) { if (username == null || username.trim().length() == 0) throw new IllegalArgumentException("Invalid constructor argument values"); this.username = username.trim(); this.firstName = firstName; this.lastName = lastName; this.email = email; this.status = status; this.joinDate = joinDate; this.lastSeen = lastSeen; this.dateOfBirth = dateOfBirth; }从异常中可以明显看出问题是由getLastSeenToLocal()方法(它试图在 中操作null对象lastSeen)引起的,我看不到它与序列化过程的相关性。Jackson 是否默认调用所有 getter,无论它们返回的字段是否列为JsonPropertys,或者我缺少某些东西(显然)?
1 回答
鸿蒙传说
TA贡献1865条经验 获得超7个赞
Jackson 默认使用类的 getters()。这样你就可以
使用 @JsonAutoDetect 使用字段
将 @JsonIgnore 添加到 getLastSeenToLocal() 方法
改进 getLastSeenToLocal() 以检查相关字段不为空(或任何其他条件)
添加回答
举报
0/150
提交
取消