Unable to map snake_case JSON to Play Form with camelCase fields (Java)
#11.171 geöffnet am 15.02.2022
Repository-Metriken
- Stars
- (12.623 Sterne)
- PR-Merge-Metriken
- (Durchschn. Merge 10T 17h) (69 gemergte PRs in 30 T)
Beschreibung
Short description
I use Play forms to validate API request bodies and bind the request to the form as follows:
final Form<TaskForm> form = formFactory.form(TaskForm.class)
.bind(messagesApi.preferred(request).lang(), request.attrs(), request.body().asJson(), 102400);
When the request body contains snake_case fields, they aren't mapped to the corresponding camelCase fields on the Play form, even when explicit @JsonProperty or @JsonNaming strategies are defined.
Request
{
"title": "Some Task",
"author_name": "John"
}
Form
@Constraints.Validate
@JsonNaming(SnakeCaseStrategy.class) // -> has no effect on play's form mapping
public class TaskForm implements Constraints.Validatable<List<ValidationError>> {
@Constraints.Required
protected String title;
@Constraints.Required
@JsonProperty("author_name") // -> has no effect either
protected String authorName;
}
Play Version
2.8.13
API
Java
Operating System
Linux inf-nb 5.16.8-arch1-1 #1 SMP PREEMPT Tue, 08 Feb 2022 21:21:08 +0000 x86_64 GNU/Linux
JDK
openjdk version "1.8.0_322"
OpenJDK Runtime Environment Corretto-8.322.06.2 (build 1.8.0_322-b06)
OpenJDK 64-Bit Server VM Corretto-8.322.06.2 (build 25.322-b06, mixed mode)
Library Dependencies
irrelevant
Expected Behavior
When sending a POST request with JSON body, where the fields are in snake_case, the Play forms should be able to map the snake_case fields to camelCase fields on the Play form (if they are annotated with a matching @JsonProperty or when a @JsonNaming strategy has been defined).
Actual Behavior
JSON request bodies with snake_case fields do not map to camelCase fields of Play forms. Even when @JsonNaming or @JsonProperty are explicitly specified.
Current workaround
My current workaround to address this issue is to simply specify the fields in the Java Play form in snake_case too. It goes against our naming convention of how to name fields in Java classes, but is the simplest workaround to cirvumvent the issue.
Reproducible Test Case
I created a public repository with a simple form, showcasing the issue: hertg/play-form-json-issue