Search code examples
javajsonapirestspring-mvc

Why camel-case fields are not recognized by API?


I have defined my request class like:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class SampleRequest {

    @NotBlank
    private String firstName;
    
    private String middleName;

    @NotBlank
    private String lastName;
}

Controller as:

    @PostMapping(path = "mydetails",  consumes = {MediaType.APPLICATION_JSON_VALUE})
    public DeferredResult<DetailsResponse> saveMyDetails(@Validated @RequestBody SampleRequest sampleRequest) {

        // some logic here

        return detailsResponse;
    }

When I'm sending my request from Postman as:

{
   "firstName":"John",
   "middleName":"For",
   "lastName":"Doe",
}

the value of all fields received at controller is null. Upon investigating, I found that it is somehow not accepting the fields in camel-case, rather it is accepting with underscore. So, I tried hitting the API with below format and it worked:

{
   "first_name":"John",
   "middle_name":"For",
   "last_name":"Doe",
}

So, why it is like this? Whatever fashion we defined in our request class, it should be same while sending the request from Postman or from app side. Why is it only working when I have to send with underscore instead of camel-case?


Solution

  • Use like this for any field you want to in your request class:

    @JsonProperty("firstName")
    private string firstName;
    
    @JsonProperty("middleName")
    private string middleName;
    
    @JsonProperty("lastName")
    private string lastName;