The mapper has a setter for PropertyNamingStrategy (Method for setting custom property naming strategy to use.)
Look how it works in the tes example:
@Test
public void namingStrategy() throws Exception {
final ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.PropertyNamingStrategyBase() {
@Override
public String translate(String s) {
return s.toUpperCase();
}
});
final String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new SomePojo("uuid_1", "user_1", "Bruce", "W.", 51));
System.out.println(json);
}
public static class SomePojo {
private String someIdAttachedToIt;
private String username;
private String fistName;
private String lastName;
private int age;
public SomePojo(String someIdAttachedToIt, String username, String fistName, String lastName, int age) {
this.someIdAttachedToIt = someIdAttachedToIt;
this.username = username;
this.fistName = fistName;
this.lastName = lastName;
this.age = age;
}
public String getSomeIdAttachedToIt() {
return someIdAttachedToIt;
}
public String getUsername() {
return username;
}
public String getFistName() {
return fistName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
}
Output:
{
"SOMEIDATTACHEDTOIT" : "uuid_1",
"USERNAME" : "user_1",
"FISTNAME" : "Bruce",
"LASTNAME" : "W.",
"AGE" : 51
}
Provided strategies (I use LOWERCASE for the examples)
PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
PropertyNamingStrategy.SNAKE_CASE
To add your strategy globally in Spring, you can do it at least in 2 ways:
- with a mapper module declared as a bean containing the naming strategy
- with a custom object mapper configured as you want
Short version:
@Configuration
public static class Config {
@Bean
public Module module() {
return new SimpleModule() {
@Override
protected SimpleModule setNamingStrategy(PropertyNamingStrategy naming) {
super.setNamingStrategy(new PropertyNamingStrategy.PropertyNamingStrategyBase() {
@Override
public String translate(String propertyName) {
// example: "propertyName" -> "PROPERTYNAME"
return propertyName.toUpperCase();
}
});
return this;
}
};
}
}
Long version:
To declare the bean for the jackson module:
// config auto scan by spring
@Configuration
public static class ConfigurationClass {
// declare the module as a bean
@Bean
public Module myJsonModule() {
return new MySimpleModule();
}
}
// jackson mapper module to customize mapping
private static class MySimpleModule extends SimpleModule {
@Override
protected SimpleModule setNamingStrategy(PropertyNamingStrategy naming) {
return super.setNamingStrategy(new MyNameStrategy());
}
}
// your naming strategy
private static class MyNameStrategy extends PropertyNamingStrategy.PropertyNamingStrategyBase {
@Override
public String translate(String propertyName) {
return propertyName.toUpperCase();
}
}
You can declare the bean in xml as well.
It won't override @JsonProperty that define the prop name explicitly.