Spring @ModelAttribute Model field mapping

家住魔仙堡 提交于 2020-06-08 19:31:58

问题


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.


回答1:


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




回答2:


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

Hope to help you!



来源:https://stackoverflow.com/questions/49985615/spring-modelattribute-model-field-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!