繁体   English   中英

将对象序列化为Json时发生NullPointerException

[英]NullPointerException when serializing object to Json

我有一个类型为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;
    }

    //.....

    public Instant getLastSeen() {
            return lastSeen;
    }

    public LocalDateTime getLastSeenToLocal() {
            return getLastSeen().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

从异常可以明显看出,问题是由getLastSeenToLocal()方法引起的(该方法试图操纵lastSeennull对象),该方法与序列化过程无关。 Jackson是否默认调用所有getter,是否将它们返回的字段列为JsonProperty ,或者(显然)缺少我?

杰克逊默认使用类的getters()。 所以你可以

  • 使用@JsonAutoDetect使用字段
  • 将@JsonIgnore添加到getLastSeenToLocal()方法
  • 改进getLastSeenToLocal()以检查相关字段不为空(或任何其他条件)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM