【问题标题】:Spring Controller JSON弹簧控制器 JSON
【发布时间】:2013-04-16 19:45:58
【问题描述】:

我有一个返回 JSON 的 Spring API,控制器方法使用StringBuilder 构建 JSON 字符串并返回 JSON 字符串,可以在浏览器中将其视为原始 JSON。

有没有更好的方法在不使用JacksonJsonView 的情况下以 JSON 格式创建/返回结果?如果我只是将结果放入HashMap<String, String> 并返回地图,那行得通吗?我试过但没有帮助。有什么好的方法吗,哪位大神可以推荐一下?

【问题讨论】:

    标签: json spring-mvc controller


    【解决方案1】:

    Spring 3.0 引入了 @ResponseBody 注释,它可以在后台将任意数据结构转换为 JSON,而无需您参与。只要确保杰克逊在类路径上,你就可以走了。例如:

    @RequestMapping(value="/getJson", method=RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getJson(@RequestParam String something) {
        Map<String, Object> output = new HashMap<String, Object>();
        output.put("date", new Date());
        output.put("input", something);
        return output;
    }
    

    spring.io blog 文章中的更多信息。

    【讨论】:

    • +1 好答案。您可能还想查看 documentation 中的控制器 支持的方法返回类型
    猜你喜欢
    • 2014-10-28
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    相关资源
    最近更新 更多