使用Jackson(ObjectMapper)如何将对象序列化为json并忽略除我注释为@JsonProperty之外的所有字段?

时间:2017-06-14 19:52:40

标签: java json jackson marshalling

更新

我在创建响应期间将我的对象包装在另一个对象中,并且该类没有任何@JsonProperty注释。将它们添加到其getter方法中可以实现这一点。

原始 我试图忽略所有字段,除了该类想要保留的少数字段,但我得到一个空对象(它忽略了所有内容)。我该怎么做?

将对象转换为json字符串:

//The marshaller
ObjectMapper marshaller = new ObjectMapper();

//Make it ignore all fields unless we specify them
marshaller.setVisibility(
    new VisibilityChecker.Std(
        JsonAutoDetect.Visibility.NONE,
        JsonAutoDetect.Visibility.NONE,
        JsonAutoDetect.Visibility.NONE,
        JsonAutoDetect.Visibility.NONE,
        JsonAutoDetect.Visibility.NONE
    )
);

//Allow empty objects
marshaller.configure( SerializationFeature.FAIL_ON_EMPTY_BEANS, false );

return marshaller.writeValueAsString( myObject );

对象:

public class MyObject
{
    private Integer id;
    private Event event;
    private String name;
    private String description;
    private Timestamp createdDate;

    public EventAction(...)
    {
        ...elided...
    }

    public Integer getId()
    {
        return id;
    }

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

    public Event getEvent()
    {
        return event;
    }

    public void setEvent(Event event)
    {
        this.event = event;
    }

    @JsonProperty
    public String getName()
    {
        return name;
    }

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

    @JsonProperty
    public String getDescription()
    {
        return description;
    }

    public void setDescription(String description)
    {
        this.description = description;
    }

    public Timestamp getCreatedDate()
    {
        return createdDate;
    }

    public void setCreatedDate(Timestamp createdDate)
    {
        this.createdDate = createdDate;
    }
}

1 个答案:

答案 0 :(得分:1)

将您的@JsonProperty移至属性/字段级别,这应该有效。

带验证的样本。

https://github.com/Flaw101/jackson-ignore-everything/tree/master

修改,

也针对反序列化测试进行了更新。