在spring boot中使用ResponseEntity返回json时遇到问题

时间:2017-12-11 00:20:05

标签: java json spring spring-boot

我正在使用Spring启动,我需要使用ResponseEntity在@RestController中传递JSON列表:

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

当我试图在邮递员中测试时,我得到一个空的身体。当我在Chrome浏览器中尝试时,我得到了:

  

Whitelabel错误页面

     

此应用程序没有/ error的显式映射,因此您将此视为后备。

     

Mon Dec 11 10:19:54 AEDT 2017   出现意外错误(type = Not Acceptable,status = 406)。   无法找到可接受的代表

4 个答案:

答案 0 :(得分:0)

据我所知,你应该指定一个映射值,尝试类似:

  

@RequestMapping(value =&#34; mymappingurl&#34;,method = RequestMethod.GET)

之后,尝试使用&#34; mymappingurl&#34;附加到它。现在,servlet容器转到后备网址主机/错误,你也没有配置任何东西,因此你会看到这个响应。

答案 1 :(得分:0)

添加

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

工作正常

答案 2 :(得分:0)

让您的方法返回 <input name="Animal & Pet" value="Animal & Pet" /> <input name="Animal & Pet" value="Animal & Pet" /> <input name="Engineering & Energy" value="Engineering & Energy" />

然后在下面重新运行:

ResponseEntity<?> getCustomers()

答案 3 :(得分:0)

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