2017-04-12 85 views
3

我有一個彈簧安置終點做一個簡單的Hello應用程序。它應該接受{「name」:「something」}並返回「Hello,something」。彈簧安置JSON後空值

我的控制器:

@RestController 
public class GreetingController { 

    private static final String template = "Hello, %s!"; 

    @RequestMapping(value="/greeting", method=RequestMethod.POST) 
    public String greeting(Person person) { 
     return String.format(template, person.getName()); 
    } 

} 

人:

public class Person { 

    private String name; 

    public Person() { 
     this.name = "World"; 
    } 

    public Person(String name) { 
     this.name = name; 
    } 

    public String getName() { 
     return this.name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 
} 

當我做出這樣

curl -X POST -d '{"name": "something"}' http://localhost:8081/testapp/greeting 

到服務的請求,我得到

Hello, World! 

看起來好像不是將json正確地反序列化到Person對象中。它使用默認的構造函數,然後不設置名稱。我發現這一點:How to create a POST request in REST to accept a JSON input?所以我嘗試添加在控制器上的@RequestBody但導致約「內容類型‘應用程序/ x-WWW窗體-urlencoded;字符集= UTF-8’不支持」的一些錯誤。我看到這裏覆蓋:Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap這表明刪除@RequestBody

我試着刪除它不喜歡的默認構造函數。

這個問題涉及空值REST webservice using Spring MVC returning null while posting JSON,但它暗示加@RequestBody但上面的衝突......

回答

7

必須設置@RequestBody告訴給春天什麼應該是使用設置你的person PARAM。

public Greeting greeting(@RequestBody Person person) { 
    return new Greeting(counter.incrementAndGet(), String.format(template, person.getName())); 
} 
+0

正如我所說的在我的描述,這導致「內容類型‘應用程序/ x-WWW窗體-urlencoded;字符集= UTF-8’不支持」 – MichaelB

+0

您的內容類型應該是'內容類型「應用程序/ json' – Zorglube

+0

您可以使用郵遞員Ø r其他一些Json客戶端來測試你的應用程序,我可能會更容易。 – Zorglube

2

必須設置 '產生' 與@RequestMapping(值= 「/問候」,方法= RequestMethod.POST)

使用以下代碼

@RequestMapping(value="/greeting", method=RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }) 
public String greeting(Person person) { 
     return String.format(template, person.getName()); 
    } 
+0

「產生」是指響應。反應很好。此外,由於它返回一個純字符串,它應該是MediaType.TEXT_PLAIN_VALUE – MichaelB

+0

嘗試'consumes = MediaType.ALL_VALUE' –

+0

@PranayKumbhalkar,'consumes = MediaType.ALL_VALUE'不是解決方案。如果您無法通過支票,解決方案不會禁用支票;該解決方案正在改變你發送的內容。 – Zorglube