How to add success / error flag by returning a list of objects as an answer

enter image description here enter image description here

 @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;
        }

Here, in the code above, I return a list of stores that consist of parts for each store, depending on location.

So my question is: can I add a success / error message when returning if I get a list of stores.

+6
source share
1 answer

As @araknoid said - you can create a wrapper:

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
}

In the controller class:

@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); 
}

If you want to return an error - you can return HttpStatus.NOT_FOUNDor just return an HttpStatus.OKerror message - it depends on your approach.

Here's the result of the controller: enter image description here

+5
source

All Articles