如何在Spring MVC的返回对象的列表为JSON(How to return a list of

2019-08-01 04:18发布

我试图让物体呈现在春季3 MVC应用程序的列表,并想通过Ajax来做到这一点。

所以在我的春节,I类有:

@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 (Internal Server Error)'

我可以成功地返回一个对象,并没有错误。 可以在春天的Json映射器(杰克逊)正确转换? 我失去了一些基本的东西?

我的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;
    }
   ...
   ...

Answer 1:

对于杰克逊,你必须创建一个强类型列表类,因为类型擦除:

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

还检查了这个答案对类似的问题。



文章来源: How to return a list of object as Json in Spring MVC