2016-10-25 9 views
3

でオブジェクトに私はそれでSpringBootアプリケーションが依存関係があります。春のブート自動JSONコントローラー

<dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-jersey</artifactId> 
    </dependency> 
    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-security</artifactId> 
    </dependency> 
    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-web</artifactId> 
    </dependency> 

次のように私は私のコントローラのメソッドを持っています。

@RequestMapping(value = "/liamo", method = RequestMethod.POST) 
@ResponseBody 
public XResponse liamo(XRequest xRequest) { 
    ... 
    return something; 
} 

私は私からJSONオブジェクトを送信XRequest型オブジェクトのいくつかのフィールドを持つAJAX経由のHTML(注釈のない単純なPOJOです)。しかし、私のJSONはコントローラメソッドでオブジェクトに構築されておらず、そのフィールドはnullです。

コントローラで自動デシリアライズが必要なのはなぜですか?

あなたは、Javaに未マーシャルJSON文字列に@RequestBody Spring MVCのアノテーションを使用することができますオブジェクトアウトオブボックスのJavaにアンマーシャリングJSONのリクエストボディの世話をする

+0

おそらく '@ RequestBody'注釈あなた' xRequest'パラメータの:http://stackoverflow.com/questions/11291933/requestbody-and-responsebody-annotations-in-spring - ところで、あなたのコントローラにspring-mvcを使用する場合、 'spring-boot-starter-jersey'は必要ありません。 – zapl

+0

@zaplのように '@ RequestBody'が見つからないし、JSONを送信している場合は、@ consumes =" application/json "を' @ RequestMapping'に追加します。 – VladoDemcak

+0

答えはそれです。見つからないRequestBody、ありがとう!あなたはそれを受け入れる答えとしてそれを書くことができますか? – kamaci

答えて

4

春ブーツは、ジャクソンが付属していますオブジェクト...例えば。

@RestController 
public class CustomerController { 
    //@Autowired CustomerService customerService; 

    @RequestMapping(path="/customers", method= RequestMethod.POST) 
    @ResponseStatus(HttpStatus.CREATED) 
    public Customer postCustomer(@RequestBody Customer customer){ 
     //return customerService.createCustomer(customer); 
    } 
} 

対応するJSONフィールド名と@JsonPropertyを使用して、エンティティのメンバー要素に注釈を付けます。

public class Customer { 
    @JsonProperty("customer_id") 
    private long customerId; 
    @JsonProperty("first_name") 
    private String firstName; 
    @JsonProperty("last_name") 
    private String lastName; 
    @JsonProperty("town") 
    private String town; 
} 
+0

リンクが壊れています。 – VedX

+0

申し訳ありません。その質問自体は削除された状態になりました。とにかくここのコンテンツのほとんどを貼り付けたコピーを削除しました。指摘してくれてありがとう。 –

+0

驚くばかりの答え、ありがとう。 –

関連する問題