【问题标题】:DTO Mapping for RESt service of type GETGET 类型的 REST 服务的 DTO 映射
【发布时间】:2018-05-23 10:09:30
【问题描述】:

在 Spring BOOT 应用程序中开发 REST 服务。

这是输入的json

{
    "rcode": 122,
    "ecode": [11, 12]
}

控制器代码

 @RequestMapping("/getPersonDTOList")
    public List < PersonDTO > getPersonDTOList(
        @RequestParam(value = "personDTO") String personDTO){

    //how can I map this to DTO

        }

//DTO

 public class PersonDTO {
        private Int rcode;
        private List<Int> ecode;

        }

如何在 spring BOOT 中将此字符串映射到 DTO,由于这是 GET,我们需要手动执行。

【问题讨论】:

  • 为什么不是POST?
  • @SudhirOjha 可能是因为请求没有改变服务器上的任何东西(即数据库)
  • 你如何将 json 传递给 rest-service?
  • @Abhijeet 我也可以将其作为请求参数传递,无需作为请求正文发送。

标签: spring spring-boot


【解决方案1】:

GET 方法不携带任何正文数据。

你要么:

  • 将您的 API 更改为 POST 方法(默认支持 @RequestMapping

    @RequestMapping("/getPersonDTOList")
    public List < PersonDTO > getPersonDTOList(@RequestBody PersonDTO person)
    
  • 将您的 API 更改为接受 @RequestParameter 而不是 @RequestBody

    @RequestMapping("/getPersonDTOList")
    public List < PersonDTO > getPersonDTOList(@RequestParam("rcode") int rcode, @RequestParam("ecode") List<Integer> ecode )
    

【讨论】:

    【解决方案2】:

    我不是很有经验,但如果你使用@RequestMapping,我认为你还必须设置一个类型:

     @RequestMapping("/getPersonDTOList", method = RequestMethod.POST ) // or GET...
    

    您还可以使用@PostMapping 、@GetMapping 等。

    @PostMapping("/getPersonDTOList")
    public PersonDTO getPersonDTOList(@RequestBody PersonDTO person){ 
         return person;
    }
    

    我认为这只对@RestController 有效

    【讨论】:

      猜你喜欢
      • 2014-11-18
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 2016-03-19
      • 2020-02-04
      • 1970-01-01
      • 2021-11-18
      相关资源
      最近更新 更多