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

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

问题描述

我正在使用Spring MVC来处理JSON POST请求。在封面下我使用基于Jackson JSON处理器构建的MappingJacksonHttpMessageConverter,并在使用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的List。 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知识的人可以了解为什么没有传递参数类型(也许这是一个bug?),但是至少有一个解决方法。

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天全站免登陆