我正在重写一个用内部框架编写的旧 REST 服务以使用 Spring。我有一个带有 POST 方法的 Controller ,该方法将参数作为 POST 或 x-www-form-urlencoded
正文。根据多个 StackOverflow 答案,我使用 @ModelAttribute 注释并创建了一个模型。
我的问题是旧的 REST API 使用蛇形命名法的属性名称 - 例如 some_property
。我希望我的 Java 代码遵循 Java 命名约定,因此在我的模型中该字段称为 someProperty
。我尝试像在 DTO 对象中那样使用 @JsonProperty 注释,但这一次不起作用。仅当模型中的字段名为 some_property
时,我才能使代码正常工作。这是我的示例代码:
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
}
}
我正在寻找注释或任何其他优雅的方式来在代码中保留 Java 命名样式,但使用 REST API 中的旧属性名称。
最佳答案
@JsonProperty
注释只能使用 JSON 格式,但您使用的是 x-www-form-urlencoded
。
如果您无法更改 POST 类型,则必须编写自己的 Jackson ObjectMapper:
@JsonProperty not working for Content-Type : application/x-www-form-urlencoded
关于java - Spring @ModelAttribute 模型字段映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59716802/