3

Is it possible to tell the JsonGenerator to serialize an object using a specific JsonView?

For example:

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

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

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.

Craig P. Motlin
  • 26,452
  • 17
  • 99
  • 126
Marty Pitt
  • 28,822
  • 36
  • 122
  • 195
  • Maybe this question helps http://stackoverflow.com/questions/7161638/how-do-i-use-a-custom-serializer-with-jackson – ssedano Dec 18 '12 at 23:27

1 Answers1

1

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();
}
Marty Pitt
  • 28,822
  • 36
  • 122
  • 195
  • For Jackson 4, you'll need a different configuration: ObjectMapper mapper = new ObjectMapper(); ObjectWriter objectWriter = mapper.writer(); if (view != null) { mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION); objectWriter = mapper.writerWithView(view); } – adam Nov 03 '15 at 23:17