簡體   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