Specifying Field Naming Policies for Jackson

I have a bean related question with json serialziation / deserialization using Jackson. I used to use GSON to do this, but now I came across a project that is already dependent on Jackson, and I would prefer not to introduce a new dependency if I can do what I already have.

So imagine I have a bean like:

class ExampleBean { private String firstField; private String secondField; // respective getters and setters } 

And then Jackson serializes him:

 { "firstField": "<first_field_value>", "secondField": "<second_field_value>" } 

I use the following code to get the result above:

 ExampleBean bean; ... ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(outStream, bean); 

However, I would like (I expected) to get the following serialization:

 { "first_field": "<first_field_value>", "second_field": "<second_field_value>" } 

I deliberately simplified my example, but I have a large beans hierarchy that I want to serialize, and I want to specify that serialized attributes should always be in snake_style (i.e. with underscores) and the corresponding bean fields should always be camelCased. Is there any way to apply such field / attribute naming policies and use them without annotating the corresponding attribute for each field?

+8
java json jackson
source share
2 answers

And yes, I found (it turned out that after 2 hours of searching I was only 30 minutes from searching for it):

 ObjectMapper mapper = new ObjectMapper(); mapper.setPropertyNamingStrategy( PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); mapper.writeValue(outStream, bean); 

I hope this will be useful for someone else.

+12
source share

Now CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES is an obsolete strategy, use SNAKE_CASE

 ObjectMapper mapper = new ObjectMapper(); mapper.setPropertyNamingStrategy( PropertyNamingStrategy.SNAKE_CASE); mapper.writeValue(outStream, bean); 
0
source share

All Articles