Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @ModelAttribute Model field mapping

I am rewriting an old REST service written in an in-house framework to use Spring. I have a Controller with a POST method which takes a parameter either as a POST or as x-www-form-urlencoded body. Following multiple StackOverflow answers, I used @ModelAttribute annotation and created a model.

My problem is that the old REST API is using a property name in snake case - say some_property. I want my Java code to follow the Java naming conventions so in my model the field is called someProperty. I tried using the @JsonProperty annotation as I do in my DTO objects but this time this didn't work. I only managed to make the code work if the field in the model was named some_property. Here is my example code:

import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/my/api/root")
public class SomethingController {

    @PostMapping("/my/api/suffix")
    public Mono<Object> getSomething(
            @RequestParam(name = "some_property", required = false) String someProperty,
            @ModelAttribute("some_property") Model somePropertyModel) {
        // calling my service here
    }

    public class Model {
        @JsonProperty("some_property")
        private String someProperty;

        private String some_property;
        // Getters and setters here
    }
}

I am searching for annotation or any other elegant way to keep the Java naming style in the code but use the legacy property name from the REST API.

like image 884
ShaMan-H_Fel Avatar asked Sep 18 '25 19:09

ShaMan-H_Fel


1 Answers

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:

@JsonProperty not working for Content-Type : application/x-www-form-urlencoded

like image 119
Bennett Dams Avatar answered Sep 20 '25 11:09

Bennett Dams