Pergunta

I have the following class:

 class Bean {
    private int x;
    private int y;
    public Bean(int x, int y) {
        this.x = x;
        this.y = y;
    }
    @JsonProperty("x")
    @JsonView(View1.class)
    public void setX(int x) {
        this.x = x;
    }
    public int getX() {
        return this.x;
    }
    @JsonProperty("y")
    public void setY(int y) {
        this.y = y;
    }
    public int getY() {
        return this.y;
    }
}

and a view:

class View1 {

}

I would expect _mapper.writerWithView(View1.class).writeValueAsString(bean) to return {"x":1}, since x is the only value that has the view attached to it, but I get {"x":1,"y":2}.

Why does it do this, and how can I make it not do this? I know I can remove the @JsonProperty("y"), but I want to still be able to serialize all values if I choose to use a normal writer instead of writerWithView.

Foi útil?

Solução

You have to disable DEFAULT_VIEW_INCLUSION feature in _mapper object.

See my example:

ObjectMapper _mapper = new ObjectMapper();
_mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
ObjectWriter objectWriter = _mapper.writerWithView(View1.class);

String json = objectWriter.writeValueAsString(bean);
System.out.println(json);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top