2

I have an API that only accepts requests with application/x-www-form-urlencoded content type.

Request Curl:

curl --location --request POST 'http://localhost:8181/inquiry' \
--header 'deviceid: 6' \
--header 'accept: application/json, text/plain, */*' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'token=03AGdBq253vhAAyXa00DAUcAPbZHD8oAW9FTeYS3r3mKQtxHCpTHv-BxaVcX3AVNcsG41KeyjdDXiJfOxtwCHMVif4yohWJ' \
--data-urlencode 'plate=ABCDEFG' \
--data-urlencode 'type=1' \
--data-urlencode 'reason_id=1'

Controller:

@PostMapping(path = "/inquiry")
public InsuranceInformationDto inquiryByPlate(
            @ModelAttribute InquiryRequestDto inquiryRequestDTO,
            @RequestHeader(value = "deviceid") Integer deviceId,
    ) { ... }

And the Dto:

@Data
public class PlateInquiryRequestDto {
    private String plate;

    @JsonProperty("type")
    private Boolean hasNaj;

    @JsonProperty("reason_id")
    private Integer reasonId;

    private String userToken;

    private Integer deviceId;

    private String token;
}

after running that code, plate and token fill in the dto, but hasNaj and reasonId are null. there is no issue if the request parameter name matches the dto property name. but @JsonProperty does not work for mapping parameters with different names.

I checked some other scenarios. when I change the request content type to json and use RequestBody this will work properly but I have to use form-urlencoded.

Also, the result is the same with and without ModelAttribute. I used @SerializedName instead of @JsonProperty but it didn't work.

I found a similar question in spring-mvc, and an answer said there isn't any annotation-based approach to solve this problem but I think spring boot maybe has a solution for me.

Mahmood Kohansal
  • 1,021
  • 2
  • 16
  • 42
  • 1
    Maybe you should use ``@FormProperty("reason_id")`` instead of ``@JsonProperty("reason_id")`` for x-www-form-urlencoded encoding as JSON. The ``@JsonProperty`` annotation can only work with the JSON format, but you're using x-www-form-urlencoded. If you can't change your POST type, you have to write your own Jackson ObjectMapper: https://stackoverflow.com/questions/38757946/jsonproperty-not-working-for-content-type-application-x-www-form-urlencoded – Sajjad Dehghani Jun 26 '22 at 04:27
  • thanks. can you send me a link to @FromProperty library? – Mahmood Kohansal Jun 26 '22 at 05:30

0 Answers0