如何在通过 ObjectMapper 序列化 class 时忽略属性

How to ignore attributes while serializing a class by ObjectMapper

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

我的Class是

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.

这里有什么问题,请帮忙

您的 @JsonProperty 注释覆盖 @JsonIgnore 注释。从 securityCode 中删除 @JsonProperty,将生成您想要的 json 输出。

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

@JsonView : http://wiki.fasterxml.com/JacksonJsonViews

@JsonFilter : http://wiki.fasterxml.com/JacksonFeatureJsonFilter