java - 让 Jackson 从 Spring Controller 返回 JSON 对象

标签 java jquery json spring-mvc jackson

我有一个 Spring MVC 后端,需要开始处理将由客户端 jQuery/AJAX 调用命中的新 URL。这些调用期望服务器返回 JSON 对象。

我正在尝试遵循我能找到的一些示例,这是迄今为止我所拥有的:

// AjaxResult.java
public class AjaxResult {
    private int answer;
    private String errMsg;

    // Getters/setters for both properties.
}

// Inside MyController.java (a Spring @Controller):
public @ResponseBody AjaxResult handleJQueryCall(@RequestParam("x") String whatever) {
    int ans = calculateSomething(whatever);

    AjaxResult result = new AjaxResult(ans);

    return result;
}

我无法编译/部署它,但是这里显然缺少一些东西...... jackson 的使用!所以我问:如何指定 Spring 将 AjaxResult 结果作为 JSON 返回到客户端?提前致谢!

最佳答案

我认为您缺少映射:

// AjaxResult.java
public class AjaxResult {
    private int answer;
    private String errMsg;

   // Getters/setters for both properties.
}

// Inside MyController.java (a Spring @Controller):
 @RequestMapping( value="/myController", method= RequestMethod.GET, produces = "application/json")
 public @ResponseBody AjaxResult handleJQueryCall(@RequestParam("x") String whatever) {
   int ans = calculateSomething(whatever);

AjaxResult result = new AjaxResult(ans);

return result;
}

关于java - 让 Jackson 从 Spring Controller 返回 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12606607/

相关文章:

java - 频繁发送到spring-websocket session : lost in transit

java - 循环引用 - Gson StackOverflowError

java - 在 spring 应用程序中将 Controller 注入(inject)服务层是一种好习惯吗?

c# - 禁用的文本框丢失 View 状态

jquery - 在 Jquery 中选择按搜索文本

java - 可以在 BigDecimal 上下文中准确地使用用小整数值初始化的 double 吗?

javascript - 悬停时使用 jQuery 将类添加到特定菜单项

javascript - Postman (JavaScript) - 如何根据 JSON 数组中的对象数量创建环境变量?

javascript - 使用 angularjs 从 json 文件中删除项目

json - 错误类型 '_InternalLinkedHashMap<String, dynamic>'不是 'String'类型的子类型