Jackson overcoming underscores in favor of camel-case
Solution 1:
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
Solution 2:
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)
Solution 3:
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
Solution 4:
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;
}
Solution 5:
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);
}