Reputation: 31
In our Spring Boot application, we are calling an third party rest API, which will return us the response data in below format:
Below response will get when data found:
{
"items": [
{
"eventType": "ABC",
"timestamp": "01-01-2020"
},
{
"eventType": "XYZ",
"timestamp": "02-02-2020"
}
]
}
Below response will get when no data found or empty:
{
"items": []
}
Actually, our rest api will return correct format data when it is success (data found). But when there is no data found (empty data), our rest api is returning like this " {} " instead of " {'items':[]} " which is not correct.
In controller, we calling the service class methods:
@Autowired
private ProductService productService;
@GetMapping("/getProduct/{productNo}")
public ResponseEntity<Product> getProduct(@PathVariable("productNo") String productNo) {
logger.debug("--- getProduct() Method Called ---");
return ResponseEntity.ok(productService.getProduct(productNo));
}
In service class, we calling the backend url using:
@Autowired
private RestTemplate restTemplate;
@Override
public Product getProduct(String productNo) {
return restTemplate.getForObject("BACK_END_URL/" + productNo, Product.class);
}
Please let us know whether we are missing anything here or done anything wrong.
Thanks in advance :)
Upvotes: 2
Views: 517
Reputation: 531
If you want to get []
when your items
is empty, initialize items
list and change items
setter in the Product
class like below:
import java.util.ArrayList;
import java.util.List;
public class Product {
private List<Item> items = new ArrayList<>();
public Product() {
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
if (items != null) {
this.items = items;
}
}
}
Result:
{
"items": []
}
Upvotes: 1
Reputation: 519
Try with this product class
public class Product {
private List<Item> items;
public Product() {
}
public Product(List<Item> items) {
super();
this.items = items;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
Upvotes: 0