Open In App

configure() Method in Jackson in JSON

In Jackson, ‘configure()’ is a method that allows you to set various configuration options for the JSON parser and generator. The ‘configure()’ method can be called on an ‘ObjectMapper’ instance, which is the main class used for converting Java objects to and from JSON.  ‘ObjectMapper’ is responsible for reading and writing JSON data in Java. The configure() method can be used to set a variety of configuration options, including:

To use the configure() method, you first need to create an instance of the ObjectMapper class:






ObjectMapper objectMapper = new ObjectMapper();

Then, you can call the configure() method on this object to set the desired configuration option:




objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Here are some examples of how to use the ‘configure()’ method in Jackson.



Examples

Example 1:

Setting serialization options: You can use ‘configure(SerializationFeature feature, boolean state)’ to set various serialization options, such as whether to include null values, how to handle dates, and how to handle enums.




ObjectMapper objectMapper = new ObjectMapper();
  
// disable writing dates as timestamps
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

Example 2:

Setting deserialization options: You can use configure(DeserializationFeature feature, boolean state) to set various deserialization options, such as how to handle unknown properties, how to handle null values, and how to handle incomplete JSON. 




ObjectMapper objectMapper = new ObjectMapper();
  
// ignore unknown properties
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Example 3: 

Setting parser/generator options: You can use configure(JsonParser.Feature feature, boolean state) and configure(JsonGenerator.Feature feature, boolean state) to set various options for the JSON parser and generator, such as whether to automatically close the underlying stream, whether to escape non-ASCII characters, and whether to pretty-print the output.




ObjectMapper objectMapper = new ObjectMapper();
  
// disable automatic stream closing
objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);

Configuring a custom naming strategy: This sets a custom naming strategy that will be used when serializing and deserializing Java object properties. In this case, the ‘SNAKE_CASE’ naming strategy converts property names to snake cases (e.g. ‘firstName’ becomes ‘first_name’).




ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);


Article Tags :