Play Framework 2.1无法处理来自控制器的JSON POST请求

use*_*754 5 java ajax json playframework

我正在尝试使用play framework 2.1(java)实现一些简单的事情:

通过jquery发布JSON数据,并从控制器中检索它.

你能告诉我哪里错了吗?

它从一个javascript调用开始:

var object = new Object();

object.title = "Hamlet";
object.author = "Bill";

var jsonData = JSON.parse(JSON.stringify(object));
jsRoutes.controllers.Application.update().ajax({
    type : 'POST',
    dataType : 'json',
    data : jsonData,
    success : function(data) {
        // I get the success
    },
    error : function(data) {
        alert('error');
    }
});
Run Code Online (Sandbox Code Playgroud)

数据似乎正确发布:Firebug控制台:

头:

Response Headers
Content-Length  2
Content-Type    text/plain; charset=utf-8
Request Headers
Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Run Code Online (Sandbox Code Playgroud)

......参数

Parametersapplication/x-www-form-urlencoded
title   Hamlet
author  Bill
Source
title=Hamlet&Author=Bill
Run Code Online (Sandbox Code Playgroud)

它在这里路线:

POST    /update       controllers.Application.update()
Run Code Online (Sandbox Code Playgroud)

这是应用程序控制器:

@BodyParser.Of(BodyParser.Json.class)
public static Result update() {
    JsonNode json = request().body().asJson();

    if(json == null){
        return badRequest("empty json"); // PROBLEM: THE JSON IS ALWAYS NULL
    }
    return ok("{}");
}
Run Code Online (Sandbox Code Playgroud)

我得到的问题是我无法从请求中检索我的参数.如果我打印它,request()似乎是空的:

DefaultRequestBody(None,None,None,None,None,None,true)
Run Code Online (Sandbox Code Playgroud)

你看到我错了吗?我怎么能得到JSON吧?

提前致谢

Bal*_*eth 5

我有完全相同的问题.除此之外dataType,您还必须设置contentType原始海报:

var jsonMsg = JSON.stringify(msg);
jsRoutes.controllers.Application.sendJson().ajax({
    type : 'POST',
    dataType : 'json',
    contentType : 'application/json; charset=utf-8',
    data : jsonMsg
});
Run Code Online (Sandbox Code Playgroud)