gpt4 book ai didi

java - 在 Spring Boot Rest 中将 GET 请求参数与 DTO 对象映射时出现问题

转载 作者:行者123 更新时间:2023-12-01 06:09:33 32 4
gpt4 key购买 nike

我已经使用 Spring REST 应用程序创建了一个 Spring Boot。

这是我的 Controller 代码。

@RestController
public class SampleController {

@RequestMapping(value = "/sample/get", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public Response getResponse(SampleDTO dto) {
Response response = new Response();

response.setResponseMsg("Hello "+dto.getFirstName());

return response;
}
}

这是我的 SampleDTO

public class SampleDTO {

@JsonProperty("firstname")
private String firstName;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}
}

这是我的 Response 对象

public class Response {

private String responseMsg;

public String getResponseMsg() {
return responseMsg;
}

public void setResponseMsg(String responseMsg) {
this.responseMsg = responseMsg;
}
}

当我尝试以这种方式访问​​服务时

http://localhost:8080/sample/get?firstName=mvg

我得到了预期的输出

{"responseMsg":"你好 mvg"}

当我尝试以这种方式访问​​服务时

http://localhost:8080/sample/get?firstname=mvg

我得到这个输出

{"responseMsg":"Hello null"}

我的问题是如何将请求参数中的“firstname”与 DTO 的“firstName”映射?

提前致谢

最佳答案

当您设置 @JsonProperty("firstname") 时,请确保导入此语句“import com.fasterxml.jackson.annotation.JsonProperty ;”。更重要的是,如果您要发送更多属性并且您的 bean 类没有,您可以在 bean 名称顶部设置 @JsonIgnoreProperties(ignoreUnknown=true) 。

您还缺少 @RequestBody 注释。您应该将其视为 getResponse 方法中的 (@RequestBody SampleDTO dto)。

关于java - 在 Spring Boot Rest 中将 GET 请求参数与 DTO 对象映射时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37675641/

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