Convert entity property camel case to snake case in json in jhipster project

Md. Shougat Hossain picture Md. Shougat Hossain · Nov 24, 2016 · Viewed 14.4k times · Source

I am working with a project that is generated with jhipster. It is a micro service architecture project.

In my entity class properties are named with camel case. So when I create a rest service it gives me json, where the json property names are as same as the entity properties.

Entity class

@Entity
@Table(name = "ebook")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "ebook")
public class Ebook implements Serializable {

    private Long id;
    private String nameBangla;
    private String nameEnglish;

Json response

{
   "id": 0,
   "nameBangla": "string",
   "nameEnglish": "string"
}

I want that my entity property will camel case, But in json response it will snake case. That is I don't want to change my entity class but I want to change my json response like bellow

{
   "id": 0,
   "name_bangla": "string",
   "name_english": "string"
}

Answer

Indivon picture Indivon · Nov 24, 2016

You have two possibilities:

Explicit naming your properties:

@JsonProperty("name_bangla")
private String nameBangla;
@JsonProperty("name_english")
private String nameEnglish;

or changing how jackson (which is used for de/serialization) works:

Jackson has a setting called PropertyNamingStrategy.SNAKE_CASE which you can set for the jackson objectmapper.

So, you need to configure Jackson for that, e.g. by adding your own object mapper:

@Configuration
public class JacksonConfiguration {

    @Bean
    public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
        return new Jackson2ObjectMapperBuilder().propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
    }
} 

As far as I know, in older version of JHipster, there was already a JacksonConfiguration to configure the JSR310 time module, but was removed later...

Adding this to your application.yml should also work:

spring.jackson.property-naming-strategy=SNAKE_CASE