【问题标题】:How to handly arbitrary json objects with spring mvc?如何使用 spring mvc 处理任意 json 对象?
【发布时间】:2010-12-09 09:26:16
【问题描述】:

我成功地将 spring-mvc 与 json 一起使用,以便在域对象和 json 对象之间进行转换。

现在,我想编写一个控制器,它只接受任何 json、验证它并以紧凑的可序列化形式为服务层提供它。 (json 字符串就足够了,任何紧凑的字节数组表示更好)。我目前的做法是这样的:

@RequestMapping(value="/{key}", method=RequestMethod.GET)
@ResponseBody
public Object getDocument(@PathVariable("username") String username,
        @PathVariable("key") String key,
        HttpServletRequest request,
        HttpServletResponse response) {
    LOGGER.info(createAccessLog(request));
    Container doc = containerService.get(username, key);
    return jacksonmapper.map(doc.getDocument(), Map.class);
}

@RequestMapping(value="/{key}", method=RequestMethod.PUT)
public void putDocument(@PathVariable("username") String username,
        @PathVariable("key") String key,
        @RequestBody Map<String,Object> document,
        HttpServletRequest request,
        HttpServletResponse response) {
    LOGGER.info(createAccessLog(request));
    containerService.createOrUpdate(username, key,document);
}

请注意,这种方法不起作用,因为我不想在 put 方法中使用 Map 而 get 方法只返回 {"this":null};。我必须如何配置我的方法?

干杯,

一月

【问题讨论】:

    标签: java json spring-mvc


    【解决方案1】:

    Spring 自动具有此功能。你只需要&lt;mvc:annotation-driven /&gt; 和你的类路径上的jackson。然后 Spring 将通过 JSON 映射器处理所有接受标头设置为 */json 的请求以及相应的响应。

    【讨论】:

    • Bozoho,JSON 映射不是问题,但我需要什么方法签名才能获得可以序列化的通用 json 对象?我目前只使用 public void put(@RequestBody MySpecificBean bean) 从 JSON 获取 bean。
    • 那么,你将如何处理任意对象?
    • 迟到的答案,正在度假;我只想序列化它并将其存储在数据库中。客户端稍后可以从服务器请求它。所以任何 String/byte[]/Stream 都足够了,它应该是紧凑的。
    【解决方案2】:

    很简单。您不需要 @RequestBody 注释。

        @RequestMapping(value="/{key}", method=RequestMethod.PUT)
        public void putDocument(@PathVariable("username") String username,
                @PathVariable("key") String key, HttpServletRequest request, HttpServletResponse response) {
    
            try {
                String jsonString = IOUtils.toString(request.getInputStream()); 
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            LOGGER.info(createAccessLog(request));
            containerService.createOrUpdate(username, key,document);
        }
    

    【讨论】:

    • 今天我可能更愿意使用@RequestBody byte[]
    猜你喜欢
    • 2013-09-21
    • 2012-10-23
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多