2015-11-28 483 views
0

我有一個包含很多服務器端邏輯所需的屬性的類,但其中一些屬於UI所需。現在,當我從類中創建一個json時,所有的屬性都被寫入json。我只想在將它轉換爲json時忽略一些值。我試過@JsonIgnore。但它不起作用。如何在通過ObjectMapper序列化類時忽略屬性

我的班級

import com.fasterxml.jackson.annotation.JsonIgnore; 
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 
import com.fasterxml.jackson.annotation.JsonProperty; 

@JsonIgnoreProperties(ignoreUnknown = true) 
public class Student { 

    @JsonProperty("id") 
    protected Integer id; 

    @JsonProperty("name") 
    protected String name; 

    /** 
    * This field I want to ignore in json. 
    * Thus used @JsonIgnore in its getter 
    */ 
    @JsonProperty("securityCode") 
    protected String securityCode; 

    public Integer getId() { 
     return id; 
    } 

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

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    @JsonIgnore 
    public String getSecurityCode() { 
     return securityCode; 
    } 

    public void setSecurityCode(String securityCode) { 
     this.securityCode = securityCode; 
    } 
} 

,我使用

public static StringBuilder convertToJson(Object value){ 
     StringBuilder stringValue = new StringBuilder(); 
     ObjectMapper mapper = new ObjectMapper(); 
     try { 
      stringValue.append(mapper.writeValueAsString(value)); 
     } catch (JsonProcessingException e) { 
      logger.error("Error while converting to json>>",e); 
     } 
     return stringValue; 
    } 

My Expected json should contain only : 

id:1 
name:abc 

but what I am getting is 
id:1 
name:abc 
securityCode:_gshb_90880..some_value. 

這裏有什麼問題,請大家幫忙

回答

相關問題