简体   繁体   English

播放控制器不接受JSON POST

[英]Play controller not accepting JSON POST

I am working on Play 1.2.4. 我正在玩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@email.com","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: MyObj具有以下字段:

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

However, the controller receives a NULL for input. 但是,控制器接收到NULL作为输入。 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)? 有人可以告诉我如何使用JSON POST请求并将其转换为对象(尤其是URL数组)吗? Thanks! 谢谢!

Try changing the variable name in your method parameters from json to body. 尝试将方法参数中的变量名从json更改为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);
    ...
    ...
}

You need to change this in your request: 您需要在请求中更改此设置:

[{"url":"http://www.google.ca"},{"url":"http://www.msn.ca"}]

For this: 为了这:

["http://www.google.ca","http://www.msn.ca"]

Because your object has an array of strings, otherwise, it will assume every element in the array is an object with one field called "url" (and obviously String do not have that field) 因为您的对象有一个字符串数组,否则,它将假定数组中的每个元素都是一个带有一个称为“ url”的字段的对象(显然,String没有该字段)

My assumption would be because you are not accessing the request, and you are never inputting a value for the String which you are accessing, giving you the NULL input. 我的假设是因为您没有访问该请求,并且您从未为正在访问的String输入一个值,因此为您提供了NULL输入。

Try accessing the JSON request through the request().body().asJson(); 尝试通过request().body().asJson();访问JSON请求request().body().asJson(); call. 呼叫。

Also have a look at http://www.playframework.org/documentation/2.0.1/JavaJsonRequests 也可以看看http://www.playframework.org/documentation/2.0.1/JavaJsonRequests

It should give you a solid idea on how to manipulate your JSON request. 它应该为您提供有关如何处理JSON请求的扎实思路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM