java - Jackson overcoming underscores in favor of camel-case

ID : 20320

viewed : 24

Tags : javajacksonjava

Top 5 Answer for java - Jackson overcoming underscores in favor of camel-case

vote vote

90

You can configure the ObjectMapper to convert camel case to names with an underscore:

objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); 

Or annotate a specific model class with this annotation:

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) 

Before Jackson 2.7, the constant was named:

PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES 
vote vote

85

If its a spring boot application, In application.properties file, just use

spring.jackson.property-naming-strategy=SNAKE_CASE

Or Annotate the model class with this annotation.

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)

vote vote

72

You should use the @JsonProperty on the field you want to change the default name mapping.

class User{     @JsonProperty("first_name")     protected String firstName;     protected String getFirstName(){return firstName;} } 

For more info: the API

vote vote

66

If you want this for a Single Class, you can use the PropertyNamingStrategy with the @JsonNaming, something like this:

@JsonNaming(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy.class) public static class Request {      String businessName;     String businessLegalName;  } 

Will serialize to:

{     "business_name" : "",     "business_legal_name" : "" } 

Since Jackson 2.7 the LowerCaseWithUnderscoresStrategy in deprecated in favor of SnakeCaseStrategy, so you should use:

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) public static class Request {      String businessName;     String businessLegalName;  } 
vote vote

52

The above answers regarding @JsonProperty and CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES are 100% accurate, although some people (like me) might be trying to do this inside a Spring MVC application with code-based configuration. Here's sample code (that I have inside Beans.java) to achieve the desired effect:

@Bean public ObjectMapper jacksonObjectMapper() {     return new ObjectMapper().setPropertyNamingStrategy(             PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); } 

Top 3 video Explaining java - Jackson overcoming underscores in favor of camel-case

Related QUESTION?