darren
darren

Reputation: 587

How to POST Json to a Play Framework Morphia controller

I first tried using play 1.2.4 with morphia 1.2.6a to post json data to my controller. That always ended with a null pointer exception somewhere inside play, so I switched to play 1.2.3 and i got a bit further, but am still confused. The post call now succeeds but the data never seems to arrive.

route



    POST /mytest    mycontroller.myposttest

mycontroller.java



    public static void myposttest(SampleObject item){
       Gson gs = new GsonBuilder().create();
       System.out.printf(gs.toJson(item));
       //NOTE: item is empty every time
    }

mytest.java



    String jsonText = "{name=\"foo\"}"; 
    Response response = POST("/mytest/","application/json",jsonText);
    //NOTE: the post call succeeds but the jsonText data is not found on the other side

The examples I have read show this as just working, but I have been messing with this for a very long time and have not figured it out. How is this intended to work?

Upvotes: 2

Views: 1268

Answers (1)

Gelin Luo
Gelin Luo

Reputation: 14373

  1. Play cannot bind Json to object direclty
  2. Your post data has no parameter named "item"

You should change your post code to:

Response response = POST("/mytest/","application/json",{item: jsonText});

And your controller code should be:

public static void myposttest(String item){
    Gson gs = new GsonBuilder().create();
    SampleObject obj = gs.fromJson(item);
    obj.save();
    ok();
}

Upvotes: 1

Related Questions