我试图让Spring 3.2 MVC返回不带默认标签的JSON响应。

例如,

@Controller
@RequestMapping("/dt")
public class DTAgentsController {

@ModelAttribute
@RequestMapping(method = RequestMethod.GET, produces = "application/json;UTF-8")
    public DTResponse agents() {
        DTResponse resp = new DTResponse();
        resp.setsEcho(1);
        resp.setiTotalDisplayRecords(10);
        resp.setiTotalRecords(50);
        return resp;
    }
}


退货

{"DTResponse":{"sEcho":1,"iTotalRecords":50,"iTotalDisplayRecords":10}}


我只想要JSON输出是

{"sEcho":1,"iTotalRecords":50,"iTotalDisplayRecords":10}


谢谢。

最佳答案

问题不在于@ModelAttribute,它仅表示您要存储或从模型中获取哪些数据。似乎您使用的是jQuery数据表,因此应将@ResponseBody添加到方法agents()中。

@RequestMapping(method = RequestMethod.GET)
@ResponseBody
    public DTResponse agents() {
        DTResponse resp = new DTResponse();
        resp.setsEcho(1);
        resp.setiTotalDisplayRecords(10);
        resp.setiTotalRecords(50);
        return resp;
    }
}

10-06 13:46