2017-06-15 148 views
1

如何在我的@RestController中映射多个豆如何在Spring @RestController中映射多个bean?

我用弹簧web的4.3.8.RELEASE.jar

我什么都试过:@RequestParam @RequestBody,@RequestAttribute,@RequestPart但没有任何工程...

package com.example.demo; 

import org.springframework.http.MediaType; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RestController; 

@RestController 
public class RestService { 

    @RequestMapping(value = "demo", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) 
    public Object[] demo(Foo foo, Bar bar) { 
     return new Object[]{foo, bar}; 
    } 

    public static class Bar { 
     public Long id; 
     public String bar; 
    } 

    public static class Foo { 
     public Long id; 
     public String foo; 
    } 
} 

我的(编码的)有效载荷是:

foo=%7B%22id%22%3A123%2C%22foo%22%3A%22foo1%22%7D&bar=%7B%22id%22%3A456%2C%22bar%22%3A%22bar1%22%7D

解码净荷:

foo={"id":123,"foo":"foo1"}&bar={"id":456,"bar":"bar1"}

请求报头:

Content-Type: application/x-www-form-urlencoded

与上面的代码,它返回:

[{"id":null,"foo":null},{"id":null,"bar":null}]

但我想要的是:

[{"id":123,"foo":"foo1"},{"id":456,"bar":"bar1"}]

感谢

+0

可能的重复:https://stackoverflow.com/questions/20622359/automatic-conversion-of-json-form-parameter-in-spring-mvc-4-0 – chuckskull

+0

@Freddy Boucher请检查我的编辑。 –

回答

0

你是创建静态内部cla ss在你的RestController中。 Spring不会自动将接收到的请求中的属性与提到的bean进行映射。请在单独的包或外部控制器中定义您的bean。然后你就可以将它与@RequestBody进行映射。

  @RestController 
      public class RestService { 

       @RequestMapping(value = "demo", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) 
       public Object[] demo(@RequestBody FooBar foobar) { 
         // your custom work 
       } 
      } 


       public class Bar { 
        public Long id; 
        public String bar; 
       } 

       public class Foo { 
        public Long id; 
        public String foo; 
       } 

// created wrapper as @RequestBody can be used only with one argument. 
       public class FooBar { 
         private Foo foo; 
         private Bar bar; 
       } 

为referece请requestBody with multiple beans

也保证了请求参数名称与您的bean的属性相匹配。(即Foo和Bar)。

+0

嗨@Sangam Belose。 豆被定义为内部类不是问题,但无论如何,我测试你的解决方案,但它不起作用。 我收到以下错误: {“timestamp”:1497515020279,“status”:415,“error”:“Unsupported Media Type”,“exception”:“org.springframework.web.HttpMediaTypeNotSupportedException”,“message”:“内容类型'application/x-www-form-urlencoded; charset = UTF-8'not supported“,”path“:”/ demo“} –

+0

@FreddyBoucher请参阅我的编辑。 –

+0

哦,我明白了,那很聪明!但仍然无效:{“timestamp”:1497569272670,“status”:415,“error”:“不支持的媒体类型”,“异常”:“org.springframework.web.HttpMediaTypeNotSupportedException”,“message”:“Content键入'application/x-www-form-urlencoded; charset = UTF-8'not supported“,”path“:”/ demo“} –