Hibernate如何返回Json值?

时间:2019-01-17 06:02:06

标签: spring hibernate

嗨,我有一个控制器方法,该方法返回客户列表并使用模型进行显示。

@Controller
public class timesheetController 
{
    @Autowired
    private CustomerDAO customerDAO;

    @GetMapping("/getCustomers")
    public String getCustomers(Model view)
    {
        //get customers from dao
        List<Customer> results = customerDAO.getCustomers(); 

        //add the customers to the model
        view.addAttribute("customers", results);

        return "list-customers";
    }   
}

但是我想将列表作为json返回以获得类似

的输出
{
    "Customer_Code": T77A,
    "Customer_Name": CustomerName1
},
{
    "Customer_Code": T77B,
    "Customer_Name": CustomerName2
}

我尝试只返回列表,如下所示

@Controller
public class timesheetController 
{
    @Autowired
    private CustomerDAO customerDAO;

    @GetMapping("/getCustomers")
    public List<Customer> getCustomers()
    {
        //get customers from dao
        List<Customer> results = customerDAO.getCustomers(); 

        return results;
    }   
}

,但是随后出现此错误,因为它似乎正在等待查看。如何返回所需的json输出? enter image description here

1 个答案:

答案 0 :(得分:1)

那么您正在尝试调用getCustomers.jsp。相反,您想要的不是JSP页面,而是JSON响应。因此,您应该进行AJAX调用(使用JQuery或其他框架或本机JS) 因此,我要做的就是以这种方式更改您的Controller类:

@Controller
public class timesheetController 
{
    @Autowired
    private CustomerDAO customerDAO;

    @GetMapping("/getCustomers", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE })
    public ResponseEntity<List<Customer>> getCustomers()
    {
        List<Customer> payload = customerDAO.getCustomers(); 
        return ResponseEntity
        .ok()
        .contentType(MediaType.APPLICATION_JSON_UTF8)
        .body(payload);
    }   
}

然后我将进行JSON调用(在此示例中,我使用的是JQuery):

var baseUrl = YOUR_WEB_APP_CONTEXT/getCustomers;
$.ajax({
    type: "GET", 
    url: baseUrl,
    success: function(data) {
        //All OK.. you should have the JSON response
    },
    error: function() {
        //Something was wrong; you chould check
    }               
});