简体   繁体   中英

Facing a issue when returning json with ResponseEntity in spring boot

I am using Spring boot and I need to pass JSON list in @RestController using ResponseEntity:

@RequestMapping(value = "", method = RequestMethod.GET)
public ResponseEntity getCustomers() {

        List<Customer> customerJsonList = new ArrayList();
        List<CustomerTable> customerList = (List<CustomerTable>) customerRepository.findAll();

        for(CustomerTable customerTable : customerList) {
            Customer customer = new Customer();
            customer.setId(customerTable.getId());
            customer.setFirstname(customerTable.getFirstname());
            customer.setLastname(customerTable.getLastname());
            customer.setAddress(customerTable.getAddress());
            customerJsonList.add(customer);
        }

        return ResponseEntity.ok(customerJsonList);
    }

When I tried to test in postman I get an empty body. When I tried in Chrome browser I am getting:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Dec 11 10:19:54 AEDT 2017 There was an unexpected error (type=Not Acceptable, status=406). Could not find acceptable representation

As far as I know, you should specify a mapping value, try something like :

@RequestMapping(value = "mymappingurl", method = RequestMethod.GET)

After that, try your url with "mymappingurl" appended to it. Right now, the servlet container goes to fallback url host/error for which you don't have anything configured either, hence you see this response.

After adding

    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.0</version>
    </dependency>

It is working fine

Have your Method return ResponseEntity<?> getCustomers()

Then Rerun below:

return new ResponseEntity<List<Customer>>(customerJsonList,HttpStatus.OK);

@RequestMapping(value = "", method = RequestMethod.GET)
public List<Customer> getCustomers() {

        List<Customer> customerJsonList = new ArrayList();
        List<CustomerTable> customerList = (List<CustomerTable>) customerRepository.findAll();

        for(CustomerTable customerTable : customerList) {
            Customer customer = new Customer();
            customer.setId(customerTable.getId());
            customer.setFirstname(customerTable.getFirstname());
            customer.setLastname(customerTable.getLastname());
            customer.setAddress(customerTable.getAddress());
            customerJsonList.add(customer);
        }

        return customerJsonList;
    }

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