Spring @ModelAttribute Model field mapping

2020-04-14 06:51发布

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.

2条回答
女痞
2楼-- · 2020-04-14 07:33

I also met a similar case you, Please replace @ModelAttribute("some_property") with @RequestBody.

Hope to help you!

查看更多
戒情不戒烟
3楼-- · 2020-04-14 07:47

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

查看更多
登录 后发表回答