如何从Spring控制器发送json响应?


问题内容

我是主题的新手。我如何使用类似的东西(使用ResponseBody)从控制器返回JSON数据

@RequestMapping(value = "/ajaxtest", method = RequestMethod.GET)
@ResponseBody
public Set<String> ajaxTest() {
Set<String> records = new HashSet<String>();
records.add("Record #1");
records.add("Record #2");
return records; 
}

我尝试使用杰克逊,但有HTTP 406错误。我应该在Spring 4.0.3中使用哪个正确的Jackson版本,使用什么算法? UPD Ajax通话

<button id="btn">Click!</button>
<script>
$("#btn").click(
function sendAjax() {
    $.ajax({
        url: "/ajaxtest",
        dataType: "json",
        success: function(data) {
            alert(data);
        },
        error:function() {
            alert("error");
        }
    });
})
</script>

问题答案:

对于转换为json请求,您必须在项目构建路径中包含以下 3个jarJackson jar 用于将
HTTP请求转换为jason格式。

还提到 headear = content-type = application / json

这些是jar文件

jackson-mapper-asl.jar
jackson-core-asl.jar
jackson-jaxrs.jar