2016-03-26 6 views
0

PostメソッドからPostメソッドを呼び出しようとしましたが、呼び出すことはできません。Playメソッドのクラスオブジェクトでポストメソッドが動作しません。

コントローラファイル:

public class UserController extends Controller{ 

    public Result getAll() { 
     List<User> users = new ArrayList<User>(); 
     users.add(new User("Vinit", "[email protected]", 25)); 
     users.add(new User("Jaimin", "[email protected]", 25)); 
     return ok(Json.toJson(users)); 
    } 

    public Result get(Long id) { 

     User user = new User(); 
     user.setId(id); 
     user.setName("Vinit"); 
     user.setEmail("[email protected]"); 
     user.setAge(25); 

     return ok(Json.toJson(user)); 

    } 

    public Result create(User user){ 

     return ok(Json.toJson(user)); 
    } 
} 

ルートファイル:

#User 
#Method.Type url    mapping with method 
GET    /user   controllers.UserController.getAll 
GET    /user/:id  controllers.UserController.get(id: Long) 
POST   /user   controllers.UserController.create 

両方が細かい作業方法/url/user/:idを得るが、私はポスト/userに少し混乱しています。私はファイルのようにコードを試しました、私は上記のエラーになった。

missing arguments for method create in class UserController; 
follow this method with `_' if you want to treat it as a partially applied function 
+0

あなたの方法を見てみることができます詳細については

は、ユーザーオブジェクトを期待していますが、それを渡していません。 – silentprogrammer

+0

私はこのjson {"id":10、 "name": "vinit"、 "email": "[email protected]"} –

+0

を渡しますが、このjsonをUser Objectに変換する方法はどのように知っていますか? – silentprogrammer

答えて

2

基本的に2つの方法があります。第2の方法は、明示的なボディパーサーを使用することです

public Result create() { 
    JsonNode json = request().body().asJson(); 
    User user = Json.fromJson(json, User.class); 
    return ok(Json.toJson(user)); 
} 

@BodyParser.Of(BodyParser.Json.class) 
public Result create() { 
    RequestBody body = request().body(); 
    User user = // some logic here 
    return ok(body.asJson()); 
} 

あなたはデフォルトのボディパーサーを(これはあなたがあなたのコメントで述べた方法である)を使用することができます

ボーナス:BodyParser.Jsonの代わりにを使用できます。BodyParser.TolerantJson:Jsonと同じですが、n Content-TypeヘッダーがJSONであることを検証します。あなたはPlay documentation regarding body parsers

関連する問題