Reputation: 383
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?
Upvotes: 1
Views: 981
Reputation: 4517
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));
Upvotes: 3