Boris Strandjev
Boris Strandjev

Reputation: 46963

Specifying the field naming policy for 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?

Upvotes: 13

Views: 13968

Answers (3)

Ruslan Omelchenko
Ruslan Omelchenko

Reputation: 5

You can use PropertyNamingStrategies class, because PropertyNamingStrategy is deprecated. ObjectMapper mapper = new ObjectMapper(); mapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);

Upvotes: 0

Deepak Tripathi
Deepak Tripathi

Reputation: 630

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);

Upvotes: 5

Boris Strandjev
Boris Strandjev

Reputation: 46963

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.

Upvotes: 19

Related Questions