Simon Zettervall
Simon Zettervall

Reputation: 1784

Is it possible to let Play Framework 1 handle a sent JSON in a post request?

Is it possible to let Play Framework 1 handle a sent JSON in a post request? The developer connecting to the backend would not like to send in key/value pairs with an ampersand as separator, he wants to send in a JSON. Problem is that the data is null, i.e name is null. Is this possible to achieve?

What I have so far:

Controller

public static void myMethod(String name) {
    Logger.info(name);
}

Routes file

POST    /test        Application.myMethod

And I send the request with header Content-Type: application/json and the data in the body { "name": "A name" }

Upvotes: 0

Views: 1162

Answers (2)

Eduardo Medeiros
Eduardo Medeiros

Reputation: 1

Actually, I don't know how this worked with you, because it is to give the error: "Stream Closed". A workarround to this would be:

   String JSON = request.params.data.get("body")[0];
   MyModel myModel = new Gson().fromJson(JSON, MyModel.class);

Upvotes: 0

Simon Zettervall
Simon Zettervall

Reputation: 1784

I did not find any auto binding so what I did was this:

MyModel myModel = new GsonBuilder().create().fromJson(new InputStreamReader(request.body), MyModel.class);

And it worked perfectly!

Upvotes: 2

Related Questions