A MJ
A MJ

Reputation: 115

How to get object writer with both pretty print and with a json view from objectmapper?

I need to create json with both pretty print and also using JsonView. How to do the same from jackson objectmapper? I get following error when I try to use both properties.

Error:The method writerWithDefaultPrettyPrinter() is undefined for the type ObjectWriter.

My code:

objectMapper.writerWithView(View.ConfigJson.class).writerWithDefaultPrettyPrinter().writeValue(file, value);

Upvotes: 1

Views: 907

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38645

The easiest way is to enable SerializationFeature.INDENT_OUTPUT on ObjectMapper:

mapper.enable(SerializationFeature.INDENT_OUTPUT);

Or use withDefaultPrettyPrinter method:

mapper
    .writerWithView(View.ConfigJson.class)
    .withDefaultPrettyPrinter()
    .writeValue(System.out, map);

You need to notice that writer* methods are declared in ObjectMapper and return ObjectWriter instance. Since that, you can use with* methods which are declared in ObjectWriter.

Upvotes: 1

Related Questions