简体   繁体   中英

Jackson / Spring Boot - serialize a snake_case model to camelCase

I am using my REST API, which is camelCase, to call a 3rd party graphQL API, which returns objects in snake_case. To do this, I am using a library to generate the mappers and model files ( graphql-java-codegen ). As a result, I end up with models that look like

class MyModel {
  public my_string;
  //...
}

I cannot force the model generation to be done in camelCase. I would like to directly return the generated models as ResponseObjects to my client, but would like the serialization to be in camelCase, without needing to copy the generated model with camelCase fields. So when returning the example, it would look like

{
  "myString": "Example str"
}

In my code generation configuration, I have the ability to add annotations at both the class and field level (but no way to customize it at each field, so no @JsonProperty("myString" ))

tl;dr: Is there some annotation / Spring Boot configuration I can use to force models with snake_case naming to serialize into camelCase, without needing to specify the @JsonProperty for every field?

You can create a custom PropertyNamingStrategy subclass and set it as the default naming strategy for one ObjectMapper mapper used only for serialization (you can check this for conversion of a string from snake_case to camelcase):

public class SnakeCaseToCamelCase extends PropertyNamingStrategy {

    @Override
    public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
        return Pattern.compile("_([a-z])")
                      .matcher(defaultName)
                      .replaceAll(m -> m.group(1).toUpperCase());
    }
}

public class MyModel {
    public String my_string = "Example str";
}

MyModel model = new MyModel();
mapper.setPropertyNamingStrategy(new SnakeCaseToCamelCase());
//it prints {"myString":"Example str"}
System.out.println(mapper.writeValueAsString(model));

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