2016-10-29 50 views
1

我正在嘗試使用dropwizard + morphia + jackson(dropwizard的默認設置)的組合,但我無法獲得@JsonIgnore@JsonIgnoreProperties的工作方式。我已經嘗試@JsonIgnoreProperties來覆蓋類的定義,我不想公開API(密碼和salt)給我的API的用戶,我也嘗試過@JsonIgnore以上的字段聲明本身以及每個getter和二傳手...現在有點虧本。Jackson和JsonIgnore隱藏祕密域

編輯:這裏的模型:

@Entity(value = "user", noClassnameStored = true) 
@Indexes({ 
    @Index(fields = { 
     @Field(value = "email", type = IndexType.ASC)}, 
     options = @IndexOptions(unique = true, sparse = true) 
    ) 
}) 
public class User { 
    @Id 
    private ObjectId id = new ObjectId(); 
    @JsonProperty 
    private String email; 
    @JsonProperty 
    private byte[] password; 
    @JsonProperty 
    private byte[] salt = SecurityUtils.getSalt(); 
    @Reference 
    private Person person = new Person(); 

    public String getId() { 
    return id.toHexString(); 
    } 

    public void setId(ObjectId id) { 
    this.id = id; 
    } 

    public String getEmail() { 
    return email; 
    } 

    public void setEmail(String email) { 
    this.email = email; 
    } 

    @JsonIgnore 
    public byte[] getPassword() { 
    return password; 
    } 

    @JsonIgnore 
    public void setPassword(String password) { 
    this.password = SecurityUtils.hashPassword(password.toCharArray(), this.getSalt()); 
    } 

    @JsonIgnore 
    public byte[] getSalt() { 
    return salt; 
    } 

    @JsonIgnore 
    public void setSalt(byte[] salt) { 
    this.salt = salt; 
    } 

    public Person getPerson() { 
    return person; 
    } 

    public void setPerson(Person person) { 
    this.person = person; 
    } 
} 

除了上面我已經試過定義使用@JsonIgnoreProperties({"password", "salt"} public class User...,類以及僅在干將,制定者有@JsonIgnore

我正在使用morphia v1.2.1來堅持。現在我有一個基本的DAO,它擴展了morphia的BasicDAO,目前大部分只是代理。如果它能提供幫助,可以發佈該代碼的片段。

+0

也許你可以發佈你的代碼? – Tibrogargan

回答

2

密碼和salt都標爲@JsonProperty,它優先於setter和getter的忽略。我想如果你刪除JsonPropety註釋(或者用JsonIgnore替換它),那些你想忽略的字段實際上會被忽略。

+0

是的,你說得對。我想我需要更多地閱讀'@ JsonProperty'。 我有一個後續問題(我可以張貼到一個新的問題,如果需要的話),這將是允許PUT密碼更新。即。如果我得到更改密碼的請求,我需要從請求中獲取原始密碼,對其進行哈希處理,然後保存它。這會發生在當前的配置? – Justin

+3

您應該能夠通過使用JsonProperty標記setter和使用JsonIgnore標記getter來使對象不對稱 - 但該字段仍需標記爲JsonIgnore(請參閱http://www.davismol.net/2015/03/21/ jackson-using-jsonignore-and-jsonproperty-annotations-to-exclude-a-property-only-from-json-deserialization /) –

+0

真棒,謝謝你的幫助! – Justin