如何在返回对象列表作为响应时添加成功/错误标志

Rah*_*mar 7 java spring-mvc

在此输入图像描述在此输入图像描述

 @RequestMapping(value = "/SubmitStep1.json", method = RequestMethod.POST,  headers = "Accept=application/json,application/xml")
        @ResponseBody
        public List<ShopDetails> showShopList(@RequestBody ShopDetails shopDetails)throws Exception{
            List<ShopDetails> shopDetailsList=new ArrayList<ShopDetails>();
            shopDetailsList=dbq.getShopDetails(shopDetails);
            return shopDetailsList;
        }
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我将返回商店列表,其中包含每个商店的详细信息.

所以,我的问题是,如果我得到商店列表,我可以在返回时添加成功/错误消息.

Opt*_*tio 6

如上所述@araknoid - 您可以创建包装器:

public class ShopListResponse {

private List<ShopDetails> shopList;

private String message;

public ShopListResponse (List<ShopDetails> shopList, String message){
this.shopList = shopList;
this.message = message;
}

// getters and setters
}
Run Code Online (Sandbox Code Playgroud)

在您的控制器类中:

@RequestMapping(value = "/SubmitStep1.json", method = RequestMethod.POST,  headers = "Accept=application/json,application/xml")
@ResponseBody
public ResponseEntity<ShopListResponse> showShopList(@RequestBody ShopDetails shopDetails)throws Exception{

List<ShopDetails> shopDetailsList = dbq.getShopDetails(shopDetails);
return new ResponseEntity<>(new ShopListResponse(shopDetailsList, "Success or error message"), HttpStatus.OK); 
}
Run Code Online (Sandbox Code Playgroud)

如果你想要返回一个错误 - 你可以返回HttpStatus.NOT_FOUND,或只是返回HttpStatus.OK并发送错误消息 - 这取决于你的方法.

这里控制器结果: 在此输入图像描述