简体   繁体   中英

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"
}

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, eg 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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM