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

时间:2019-01-27 21:00:14

标签: java json serialization jackson

我有一个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()方法引起的(该方法试图操纵null中的lastSeen对象),我可以将其与序列化过程相关联没看到杰克逊是否会默认调用所有吸气剂,无论它们返回的字段是否列为JsonProperty,还是(显然)缺少我的东西?

1 个答案:

答案 0 :(得分:1)

Jackson默认情况下使用class的getters()。 所以你可以

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