如何在ObjectMapper序列化类时忽略属性

时间:2015-11-28 09:16:20

标签: json jackson spring-mvc-test objectmapper

我有一个具有许多属性的类,这些属性是服务器端逻辑所必需的,但是UI中需要一些属性。现在,当我从类创建一个json时,所有属性都写入json。我只想在转换为json时忽略某些值。我试过@JsonIgnore。但它没有用。

我的班级

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.

这里有什么问题,请帮忙

1 个答案:

答案 0 :(得分:2)

您的@JsonProperty注释会覆盖@JsonIgnore注释。从@JsonProperty删除securityCode,将生成所需的json输出。

如果您想要更高级的忽略/过滤,请查看:

@JsonViewhttp://wiki.fasterxml.com/JacksonJsonViews

@JsonFilterhttp://wiki.fasterxml.com/JacksonFeatureJsonFilter