作为Rest服务中的参数的对象数组

时间:2015-02-26 18:14:05

标签: java json rest spring-mvc

我有一个接收一个对象数组的休息服务,我需要将json信息转换回对象List;我的堆栈是在Spring 4之上构建的

我得到了这个服务定义:

@RequestMapping(value = "/services/crud/dangers/createDanger", method = RequestMethod.GET)
    public @ResponseBody GenericServiceReturn createDanger(
            @RequestParam(value = "postionId", required = true) Long positionId,
            @RequestParam(value = "dangerName", required = true) String dangerName,
            @RequestParam(value = "type", required = true) Integer type,
            @RequestParam(value = "description", required = true) String description,
            @RequestParam(value = "words", required = true) List<RestWord> words)

如您所见,参数字是一个RestWord列表,其定义如下:

public class RestWord {
    private long id = -1;
    private String name;
    private long type = -1;

此外,我已经像这样定义了转换器:

public class RestWordConverter implements Converter<String, RestWord>{
    private static final Logger log = LoggerFactory
            .getLogger(RestWordConverter.class);

    @Override
    public RestWord convert(String text) {
        // TODO Auto-generated method stub
        log.info(text);
        return new RestWord();
    }

}
到目前为止,你可以看到的逻辑并不多,也就像这样在mvc上下文中注册了转换器。

<mvc:annotation-driven conversion-service="conversionService" />

<beans:bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" >
        <beans:property name="converters">
            <beans:list>
                <beans:bean class="co.com.lineascontrol.core.endpoints.converters.RestWordConverter"/>
            </beans:list>
        </beans:property>
    </beans:bean>  

问题是,为json消息的每一小部分调用转换器类,以说明传入消息的一个简单示例:

String words = "[{\"id\":0,\"name\":instalar,\"type\":-1},{\"id\":0,\"name\":ventilacion,\"type\":-1},{\"id\":0,\"name\":tunel,\"type\":-1}]";

我在服务器输出端得到这个:

c.c.l.c.e.c.RestWordConverter - [{"id":0
c.c.l.c.e.c.RestWordConverter - "name":instalar
c.c.l.c.e.c.RestWordConverter - "type":-1}
c.c.l.c.e.c.RestWordConverter - {"id":0
c.c.l.c.e.c.RestWordConverter - "name":ventilacion
c.c.l.c.e.c.RestWordConverter - "type":-1}
c.c.l.c.e.c.RestWordConverter - {"id":0
c.c.l.c.e.c.RestWordConverter - "name":tunel
c.c.l.c.e.c.RestWordConverter - "type":-1}]

这意味着对于消息的每个部分都会调用转换器函数一次,这样就无法将传入的字符串转换为特定的对象。

我也有像这样定义的标准Json转换器:

<beans:bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <beans:property name="messageConverters">
            <beans:list>
                <beans:ref bean="jsonMessageConverter" />
            </beans:list>
        </beans:property>
    </beans:bean>

    <!-- Configure bean to convert JSON to POJO and vice versa -->
    <beans:bean id="jsonMessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </beans:bean>

我认为转换器应该被定义为json转换器,而不是mvc的转换服务,但我还没有设法找到关于此的示例或文档。

解决方案

嗨,如果其他人正在努力解决这个问题,我设法让所有事情都能正常运行。

首先,如果你是Rest的新手,我发现这篇简单的文章解释了基本的,但非常重要的东西:

http://www.drdobbs.com/web-development/restful-web-services-a-tutorial/240169069?pgno=1

之后,我理解了大部分问题,所以最后这是我的服务界面:

@RequestMapping(value = "/services/crud/dangers/createDanger", method = RequestMethod.POST)
    public @ResponseBody GenericServiceReturn createDanger(
            @RequestBody List<RestWord> words,
            @RequestParam(value = "postionId", required = true) Long positionId,
            @RequestParam(value = "dangerName", required = true) String dangerName,
            @RequestParam(value = "type", required = true) String type,
            @RequestParam(value = "description", required = true) String description) {

这是适当的方式来调用它!

List<RestWord> restWordList = new ArrayList<RestWord>();

            //put some values in the list! or whatever object you are using

            url = "http://localhost:8080/LineasControllBussinesLayer/rest/services/crud/dangers/createDanger";

            //add the uri params
            Map<String, Object> requestParams = new HashMap<String, Object>();
            requestParams.put("postionId", 1l);
            requestParams.put("dangerName", dangerName);
            requestParams.put("type", DANGER_TYPE.ACTIVITIE);
            requestParams.put("description", "actividad repeligrosa");

            // Create the request body as a MultiValueMap

            System.out.println(restWordList);
            //see how the HttpEntity is created with the first parameter as the object, and the second are the header, in my case I use the headers to aunteticate
            HttpEntity<List<RestWord>> entity2 = new HttpEntity<List<RestWord>>(restWordList, headers);


            //then just call the service!!!
            System.out.println(restTemplate.postForObject(url, entity2, String.class, requestParams));

请记住,这只是测试代码,实际请求应该包含在请求对象中,并且所有内容都应该放在请求正文中

1 个答案:

答案 0 :(得分:1)

我建议使用@Resquestbody将json映射到对象。请注意将其与@RequestParam结合使用,因为它可能有效或未给定版本,并且必须按特定顺序(在这种情况下尽量避免使用@ResquestParam。)

看看:Spring MVC - Why not able to use @RequestBody and @RequestParam together 阅读直到最后一条评论。