Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying the field naming policy for Jackson

Tags:

java

json

jackson

I have question related to bean to json serialziation/deserialization using Jackson. Previously I have used GSON to do that, but now I am faced with a project that already depends on Jackson and I would prefer not to introduce new dependency if I can do with what I already have at hand.

So imagine I have a bean like:

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

And then Jackson serializes it to:

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

I am using the following code to produce the above result:

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

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

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

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

like image 959
Boris Strandjev Avatar asked Mar 02 '12 12:03

Boris Strandjev


2 Answers

Now CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES is the deprecated strategy use SNAKE_CASE instead

ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(
    PropertyNamingStrategy.SNAKE_CASE);
mapper.writeValue(outStream, bean);
like image 93
Deepak Tripathi Avatar answered Oct 22 '22 23:10

Deepak Tripathi


And yes I found it (it turned out that after 2 hours of searching I had been only 30 minutes away from finding it):

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

Hopefully this will turn out to be helpful to somebody else too.

like image 20
Boris Strandjev Avatar answered Oct 22 '22 23:10

Boris Strandjev