简体   繁体   English

RequestBody 中的 POST 数组到 Spring Controller 作为对象列表

[英]POST array in RequestBody to Spring Controller as List of Objects

I'm fairly new to Spring, and I've looked at many posts about similar scenarios, but I have yet to figure this out.我对 Spring 还很陌生,我看过很多关于类似场景的帖子,但我还没有弄清楚。

I'm trying to alter an existing (working) endpoint in my project to pass an array of Region objects from Angular frontend to a list or other collection in Spring backend.我正在尝试更改项目中的现有(工作)端点,以将Region对象数组从 Angular 前端传递到 Spring 后端中的列表或其他集合。 Most of my attempts have resulted in the error: Bad argument(s) for enum JSON parse error: Cannot deserialize instance of java.util.ArrayList<com.cigna.apps.shapeup.domain.Region> out of START_OBJECT token .我的大多数尝试都导致了错误: Bad argument(s) for enum JSON parse error: Cannot deserialize instance of java.util.ArrayList<com.cigna.apps.shapeup.domain.Region> out of START_OBJECT token .

Here is my frontend API call:这是我的前端 API 调用:

createCampaignReports(apiRoot: HateoasResponse, campaignId: number, regionList: Region[]): Observable<Action> {
    if (hasHref(apiRoot, this.links.reports)) {
      let params: HttpParams = new HttpParams();
      params = params.set('campaignId', campaignId.toString());
      return this.httpClient.post(getHref(apiRoot, this.links.reports), {regionList}, {params: params})

    ...other code...

    }
  }

And here is a stringified sample array from my frontend:这是来自我的前端的字符串化示例数组:

[
  {
    "sid": 2,
    "region": "New Zealand"
  },
  {
    "sid": 18,
    "region": "Middle East"
  },
  {
    "sid": 19,
    "region": "Kenya"
  }
]

My Spring Controller:我的 Spring Controller:

@PostMapping("/reports")
    ResponseEntity<ApiResponse> generateReports(@RequestParam(value = 'campaignId', required = true) Integer campaignId,
                                                @RequestBody (required = false) List<Region> regionList,
                                                HttpServletRequest request,
                                                HttpServletResponse response) {
...other code...

def user = userService.getUser(userId)
def report = portalService.generateReport(user, campaignId, regionList)

...

And finally, my Region class in the backend:最后,我在后端的区域 class :

class Region extends BaseEntity {

    String region

    int age
}

You could create wrapper class (DTO) for regions list, like:您可以为区域列表创建包装器 class (DTO),例如:

public class RegionsRequest {
    private List<Region> regions;
    // getters/setters

Update your controller accordingly:相应地更新您的 controller:

@PostMapping("/reports") 
ResponseEntity<ApiResponse> generateReports(
    @RequestParam(value = 'campaignId', required = true) Integer campaignId, 
    @RequestBody (required = false) RegionsRequest regions, 
    HttpServletRequest request, 
    HttpServletResponse response) { 
    // other code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM