ajax – 如何在Spring MVC中将对象列表作为Json返回

我正在尝试获取要在Spring 3 MVC应用程序上呈现的对象列表,并希望通过Ajax执行此操作.

所以在我的Spring课程中我有:

@RequestMapping(value = "/viewSearchEnquiriesAjax", method = RequestMethod.GET, headers = "Accept=application/json")
public @ResponseBody List<Enquiry> getEnquiriesBySearchAjax(@RequestParam String name) {
    Search search =  new Search();
    search.setFirstName(name);
    return searchEnquiries(search);
}

但是当运行它时我得到500(内部服务器错误).当我在浏览器中调试为’GET http:// localhost:8080 / SpringMVC / viewSearchEnquiriesAjax?name = peter 500(内部服务器错误)时,这表明了这一点.

我可以成功返回一个没有错误的对象. Spring Json mapper(Jackson)可以正确转换吗?我错过了什么基本的东西?

我的javascript如下:

function doAjaxPost() {
// get the form values
var firstName = $('#firstName').val();
$.getJSON("/SpringMVC/viewSearchEnquiriesAjax", { name: firstName }, function(result) {
    alert("Success");
 });

}

我的查询对象是一个实体:

@Entity
@Table(name = "enquiries")
public class Enquiry implements java.io.Serializable{

    private static final long serialVersionUID = -5093725544297637792L;

    protected Long id;
    protected Date created = new Date();
    ...
    ...

    public Enquiry() {
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", unique = true, nullable = false)
    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }
   ...
   ...
最佳答案
对于Jackson,你必须创建一个强类型列表类,因为类型擦除:

public class EnquiryList extends ArrayList<Enquiry> {
}

然后从您的控制器返回此列表:

@RequestMapping(value = "/viewSearchEnquiriesAjax", method = RequestMethod.GET, headers = "Accept=application/json")
public @ResponseBody EnquiryList getEnquiriesBySearchAjax(@RequestParam String name) {
    EnquiryList list = new EnquiryList();
    ...
    return list;
}

另请查看类似问题的this answer.

转载注明原文:ajax – 如何在Spring MVC中将对象列表作为Json返回 - 代码日志