Some cool tips of Jackson

Some cool tips of Jackson

from Ted M. Young

  • To make the JSON easier to read, you can tell ObjectMapper to use a “pretty printer”,

ObjectMapper objectMapper = new ObjectMapper();

Book jacksonCookbook = new JacksonCookbook();

String json = objectMapper

.writerWithDefaultPrettyPrinter()

.writeValueAsString(jacksonCookbook);

System.out.println(json);

 

If you always want to pretty-print the output, you can configure the ObjectMapper instance directly using the SerializationFeature class:


ObjectMapper objectMapper = new ObjectMapper();

objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

 

The enable method here turns on the INDENT_OUTPUT feature, which tells Jackson to use the DefaultPrettyPrinter when serializing your objects. The code

objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true)

  • If you have property values in your data that can be null, but don’t want them serialized when they are, you can do the following to make the setting global for all uses of this objectMapper reference:

objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

If you only want to do this on a per-class basis, you can add the @JsonInclude annotation above the class or interface definition:


@JsonSerialize(include = Inclusion.NON_NULL)
public class HasNullValues {private String optionalSecondAddress; // nullable field

 

  • Sometimes you’ll want the properties that in your JSON output to be in a specific order, perhaps because you have tests or clients that rely on the ordering (I’d try to avoid that, but sometimes it’snot under your control), or you want it to be easier to find a certain property when looking at the JSON during debugging.

To order on a per-class basis, use the @JsonPropertyOrder annotation:


@JsonPropertyOrder({“id”, “symbol”})
public class Currency {public String symbol;

public String shortName;

public String longName;

public long id;

}

This will ensure that the id property will be first, followed by the symbol property, with the rest in an undetermined order.

If you wanted them simply in alphabetic order, you would use the alphabetic parameter in the annotation:

@JsonPropertyOrder(alphabetic = true)

If you always want the properties sorted alphabetically, configure the ObjectMapper instance directly:

objectMapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);

Note that the above settings won’t affect the order of the contents of any maps that you have (e.g., a HashMap). If you want the output of maps to be ordered by their keys, you’ll need to turn on the ORDER_MAP_ENTRIES_BY_KEYS feature:

objectMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);

Advertisements