杰克逊 - 在JsonSerializer中使用JsonView?

时间:2012-12-18 23:24:15

标签: java jackson

是否可以告诉JsonGenerator使用特定的JsonView序列化对象?

例如:

@Data
class Author {
    @JsonSerialize(using=CustomSerializer.class)
    List<Book> bestFiveBooksOfAllTime;
};
@Data
class Book extends BaseEntity
{
    @JsonView(SummaryView.class)
    private String title;
    @JsonView(SummaryView.class)
    private String author;
    private String review;
}

在我的CustomSerializer中,我希望能够做到以下几点:

public class CustomSerializer extends JsonSerializer<Author> {

    @Override
    public void serialize(Author value, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {
        jgen.writeStartObject();
        for (Book book : value.getBestFiveBooksOfAllTime()) {
                    // Something like the following...
            jgen.writeObjectFieldUsingView(book.getId().toString(), book, SummaryView.class);
        }
        jgen.writeEndObject();
    }
}

即在上面的场景中,我希望结果包含bestFiveBooksOfAllTime的地图,其中的值只是图书的SummaryView

1 个答案:

答案 0 :(得分:1)

这是我最终使用的解决方案 - 请告知是否有更好的方法

@Override
public void serialize(Author value, JsonGenerator jgen,
        SerializerProvider provider) throws IOException,
        JsonProcessingException {

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);
    mapper.setSerializationConfig(mapper.getSerializationConfig().withView(SummaryView.class));

    jgen.writeStartObject();
    for (Book book : value.getBestFiveBooksOfAllTime()) {
        jgen.writeFieldName(book.getId().toString());
        mapper.writeValue(jgen, book);
    }
    jgen.writeEndObject();
}