REST 与 Spring 和 Jackson 完整数据绑定 [英] REST with Spring and Jackson full data binding

查看:35
本文介绍了REST 与 Spring 和 Jackson 完整数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Spring MVC 来处理 JSON POST 请求.在幕后,我使用 MappingJacksonHttpMessageConverter 构建在 Jackson JSON 处理器上,并在您使用 mvc:annotation-driven 时启用.

I'm using Spring MVC to handle JSON POST requests. Underneath the covers I'm using the MappingJacksonHttpMessageConverter built on the Jackson JSON processor and enabled when you use the mvc:annotation-driven.

我的一个服务收到一个操作列表:

One of my services receives a list of actions:

@RequestMapping(value="/executeActions", method=RequestMethod.POST)
    public @ResponseBody String executeActions(@RequestBody List<ActionImpl> actions) {
        logger.info("executeActions");
        return "ACK";
    }

我发现 Jackson 将 requestBody 映射到 java.util.LinkedHashMap 项目列表(简单数据绑定).相反,我希望将请求绑定到类型对象列表(在本例中为ActionImpl").

I have found that Jackson maps the requestBody to a List of java.util.LinkedHashMap items (simple data binding). Instead, I would like the request to be bound to a List of typed objects (in this case "ActionImpl").

我知道如果您直接使用 Jackson 的 ObjectMapper,这很容易做到:

I know this is easy to do if you use Jackson's ObjectMapper directly:

List<ActionImpl> result = mapper.readValue(src, new TypeReference<List<ActionImpl>>() { }); 

但我想知道在使用 Spring MVC 和 MappingJacksonHttpMessageConverter 时实现这一目标的最佳方法是什么.有什么提示吗?

but I was wondering what's the best way to achieve this when using Spring MVC and MappingJacksonHttpMessageConverter. Any hints?

谢谢

推荐答案

我怀疑问题是由于类型擦除造成的,即没有传递泛型参数类型,可能只传递了 actions.getClass();这将给出等效于 List<; 的类型.?>.

I suspect problem is due to type erasure, i.e. instead of passing generic parameter type, maybe only actions.getClass() is passed; and this would give type equivalent of List< ?>.

如果这是真的,一种可能性是使用中间子类,例如:

If this is true, one possibility would be to use an intermediate sub-class, like:

public class ActionImplList extends ArrayList<ActionImpl> { }

因为即使只传递了类,这也会保留类型信息.那么:

because this will the retain type information even if only class is passed. So then:

public @ResponseBody String executeActions(@RequestBody ActionImplList actions)

会成功.不是最佳的,但应该有效.

would do the trick. Not optimal but should work.

我希望有更多 Spring MVC 知识的人可以阐明为什么没有传递参数类型(也许这是一个错误?),但至少有一个解决方法.

I hope someone with more Spring MVC knowledge can shed light on why parameter type is not being passed (perhaps it's a bug?), but at least there is a work around.

这篇关于REST 与 Spring 和 Jackson 完整数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆