I'm using Jackson with Spring. I have a few methods like this:
@RequestMapping(value = "/myURL", method = RequestMethod.GET)
public @ResponseBody Foo getFoo() {
// get foo
return foo;
}
The class Foo that's serialized is quite big and has many members. The serialization is ok, using annotation or custom serializer.
The only thing I can't figure out is how to define the naming convention. I would like to use snake_case for all the serializations.
So how do I define globally the naming convention for the serialization?
If it's not possible, then a local solution will have to do then.
The @JsonPOJOBuilder annotation is used to configure a builder class to customize deserialization of a JSON document to recover POJOs when the naming convention is different from the default. The names of the bean's properties are different from those of the fields in JSON string.
The @JsonIdentityInfo annotation is used when an object has a parent-child relationship in the Jackson library. The @JsonIdentityInfo annotation is used to indicate the object identity during the serialization and deserialization process.
Jackson mixins is a mechanism to add Jackson annotations to classes without modifying the actual class. It was created for those cases where we can't modify a class such as when working with third-party classes. We can use any Jackson annotation but we don't add them directly to the class.
Not sure how to do this globally but here's a way to do it at the JSON object level and not per each individual property:
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class Foo {
private String myBeanName;
//...
}
would yield json:
{
"my_bean_name": "Sth"
//...
}
Actually, there was a really simple answer:
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder b = new Jackson2ObjectMapperBuilder();
b.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
return b;
}
I added it in my main like so:
@SpringBootApplication
public class Application {
public static void main(String [] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder b = new Jackson2ObjectMapperBuilder();
b.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
return b;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With