I am working with spring-boot, in my controller, I am receiving a formData. I'm mapping the request to the POJO using the @ModelAttribute however, the formData names are not uniform. In this case, @JsonProperty is not helping. I was looking for some annotation or way so I can rename these fields while mapping.
Curl sample-
curl --location --request POST 'http://localhost:8080/api/demo' \
--header 'Authorization: Bearer ' \
--form 'deviceID="123"' \
--form 'ASN="123"' \
--form 'portal="demoportal"' \
--form 'str_ScanData=@"/D:/sample.xml"'
My Controller sample-
@PostMapping(path = "/demo", consumes = {"multipart/form-data"}) public ResponseEntity<demoDto> demoController(
@ModelAttribute DemoRequest demoRequest)
My POJO for Request -
Class DemoRequest {
// what i have right now
private String deviceID;
private String ASN;
private String portal;
private MultipartFile str_ScanData;
// getter setters constructor
// What I want to have
private String deviceId; //camelcase
private String asn; //rename
private String portal;
private MultipartFile uploadedFile; //rename
}
I am new to using forums and spring-boot. Please let me know if I am on wrong track or have not posted any relevant info.
That's a pretty old question, but I just came across the same problem and figured out that Spring (at least in spring-webflux
, but it should work the same for spring-web
) makes use of @ConstructorProperties
annotation in ModelAttributeMethodArgumentResolver
.
That means the following is possible for a custom field naming inside a ModelAttribute
:
public class DemoRequest {
private final String deviceId;
private final String asn;
private final String portal;
private final MultipartFile uploadedFile;
@ConstructorProperties({"deviceID", "ASN", "portal", "str_ScanData"})
public DemoRequest(String deviceId, String asn, String portal, MultipartFile uploadedFile) {
this.deviceId = deviceId;
this.asn = asn;
this.portal = portal;
this.uploadedFile = uploadedFile;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With