3

Play controller does not accept JSON POST

 2 years ago
source link: https://www.codesd.com/item/play-controller-does-not-accept-json-post.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Play controller does not accept JSON POST

advertisements

I am working on Play 1.2.4.
I have set up the routes like this:

POST    /index    Application.index(format:'json')

The controller is like this:

public static void index(String json) {

    Logger.info("content type: %s", request.contentType);
    Logger.info("json string: %s", json);
    MyObj obj = new Gson().fromJson(json, MyObj.class);
    ...
    ...
}

And my curl request is like this:

curl -v -H "Content-Type: application/json" -X POST -d '{"name":"John Smith","email":"[email protected]","value1":"Value one","value2":"Value two","urls":[{"url":"http://www.google.ca"},{"url":"http://www.msn.ca"}]}' http://localhost:9000/index

MyObj has the following fields:

public String name;
public String email;
public String value1;
public String value2;
public String[] urls;

However, the controller receives a NULL for input. What am I doing wrong? Can someone show me how to consume a JSON POST request and convert it to an object (in particular the array of urls)? Thanks!


Try changing the variable name in your method parameters from json to body.

public static void index(String body) {

    Logger.info("content type: %s", request.contentType);
    Logger.info("json string: %s", body);
    MyObj obj = new Gson().fromJson(body, MyObj.class);
    ...
    ...
}




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK