2017-06-15 149 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「} –