Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"
}
like image 280
Md. Shougat Hossain Avatar asked Nov 24 '16 09:11

Md. Shougat Hossain


2 Answers

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
like image 172
Indivon Avatar answered Nov 17 '22 12:11

Indivon


Also you can use annotation to define naming strategy per class.

Little example in Kotlin:

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy::class)
data class Specialization(val altUrl: String, val altId: Int, val altName: String)
like image 45
Sonique Avatar answered Nov 17 '22 13:11

Sonique