简体   繁体   中英

Response returned from my Spring Boot Rest API is not same as the backend API provided to my rest API

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 :)

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": []
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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