杰克逊 - 在JsonSerializer中使用JsonView? [英] Jackson - use a JsonView within a JsonSerializer?

查看:124
本文介绍了杰克逊 - 在JsonSerializer中使用JsonView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to tell the JsonGenerator to serialize an object using a specific 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 ,我希望能够做一些事情:

In my CustomSerializer, I'd like to be able to do something along the lines of:

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

Ie., in the above scenario, I'd like the result to contain a map of bestFiveBooksOfAllTime, where the value is just the SummaryView of the book.

推荐答案

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

Here's the solution I ended up using -- please advise if there's a better way

@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();
}

这篇关于杰克逊 - 在JsonSerializer中使用JsonView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆