【问题标题】:NullPointerException when serializing object to Json将对象序列化为 Json 时出现 NullPointerException
【发布时间】:2019-01-27 21:00:13
【问题描述】:

我有一个 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() 方法引起的(它试图操作lastSeen 中的null 对象),我看不到它与序列化过程的相关性。 Jackson 是否默认调用所有 getter,无论它们返回的字段是否列为JsonPropertys,还是我缺少某些东西(显然)?

【问题讨论】:

    标签: java json serialization jackson


    【解决方案1】:

    Jackson 默认使用类的 getters()。 所以你可以

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-13
      • 2013-01-17
      • 1970-01-01
      • 2014-08-14
      • 2023-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多