Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In springboot, how to rename Form-data fields while mapping using @ModelAttribute?

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.

like image 470
Stalwart Avatar asked Sep 02 '25 15:09

Stalwart


1 Answers

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;
    }
}
like image 104
Maciej Dobrowolski Avatar answered Sep 05 '25 07:09

Maciej Dobrowolski