简体   繁体   中英

How to convert camel case to lower case with underscores in a REST API?

I am using Quarkus and Microprofile OpenAPI to map entities in REST APIs. I can convert my camel case named properties to lower case with underscores in the following way:

@Schema(name = "first_name")
private String firstName;

However it is inconvenient as I have to do this everywhere across the project.

Question: Is there a way to do it automatically for all properties without having to specify the mapping in the annotation?

I went through the documentation of Quarkus and Microprofile but haven't found how it can be achieved.

If you want to make this behaviour the default one, you have to configure this in the object mapper that is responsible for serialization/deserialization of objects to json. In Quarkus, you can use either Jackson or JsonB for object mapping.

For Jackson, you can control the behaviour of field names using PropertyNamingStrategy which you want to set to SNAKE_CASE . To set this globally, create an ObjectMapperCustomizer like so:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import io.quarkus.jackson.ObjectMapperCustomizer;

import javax.inject.Singleton;

@Singleton
public class ObjectMapperConfig implements ObjectMapperCustomizer {

    @Override
    public void customize(ObjectMapper objectMapper) {
         objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
    }
}

You can control many more aspects of serialization eg ignore unknown props during deserialization, date formatting, etc.

You need to have a dep to quarkus-resteasy-jackson :

<dependency>
   <groupId>io.quarkus</groupId>
   <artifactId>quarkus-resteasy-jackson</artifactId>
</dependency>

If you want to use JsonB ( quarkus-resteasy-jsonb ) then you can try it with the following JsonbConfigCustomizer

import io.quarkus.jsonb.JsonbConfigCustomizer;

import javax.inject.Singleton;
import javax.json.bind.JsonbConfig;
import javax.json.bind.config.PropertyNamingStrategy;
@Singleton
public class JsonBCustomizer implements JsonbConfigCustomizer {

    public void customize(JsonbConfig config) {
        config.withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES);
    }
}

I found this in the openapi doc:

You can control how the Schema property names are dumped by setting the micronaut.openapi.property.naming.strategy system property. It accepts one of the following jackson's PropertyNamingStrategy: - SNAKE_CASE, - UPPER_CAMEL_CASE, - LOWER_CAMEL_CASE, - LOWER_CASE and - KEBAB_CASE.

For further details see Hibernate 5 Naming Strategy Configuration by baeldung .

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