ShaMan-H_Fel
ShaMan-H_Fel

Reputation: 2209

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.

Upvotes: 4

Views: 5402

Answers (2)

TH Dragon
TH Dragon

Reputation: 1

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

Hope to help you!

Upvotes: -1

Bennett Dams
Bennett Dams

Reputation: 7033

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

Upvotes: 3

Related Questions