gpt4 book ai didi

java - Spring @ModelAttribute 模型字段映射

转载 作者:行者123 更新时间:2023-11-30 10:16:37 24 4
gpt4 key购买 nike

我正在重写一个用内部框架编写的旧 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/49985615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com