2

我正在尝试将 Json 数组传递给 Grails 控制器,然后再传递给 Java 类。我不知道如何正确地将我的参数传递给 Java 类。这是相关的代码。

AJAX 发布:

  $('#matrixForm').submit(function(e) {
        e.preventDefault();

    var matrixArray = $(this).serializeArray();

    $.ajax({  
        type: "POST",  
        data: matrixArray,  
        url: "/turingpages/factorize/create",
        success: function(data) {
            //USE DATA
        }  
    });  
    }); 

Grails 控制器:

...
    def create() {

        MatrixFactorization m = new MatrixFactorization(params)
        Gson gson = new Gson()
        def jsonMatrix = gson.toJson(m.answer)
        render jsonMatrix
    }
...

矩阵分解构造函数:

public MatrixFactorization(JsonElement jsonarray) {
    BlockRealMatrix R = GsonMatrix.toMatrix(jsonarray);
    this.run(R);
}

我的控制台将我的 Json 数组显示为:

[{name:"00", value:"1"}, {name:"01", value:"2"}, {name:"02", value:"3"}, {name:"10", value:"4"}, {name:"11", value:"0"}, {name:"12", value:"4"}, {name:"20", value:"0"}, {name:"21", value:"4"}, {name:"22", value:"2"}] 

我的堆栈跟踪是:

| Error 2013-01-18 00:30:23,792 [http-bio-8080-exec-4] ERROR errors.GrailsExceptionResolver  - GroovyRuntimeException occurred when processing request: [POST] /turingpages/factorize/create - parameters:
21: 4
20: 0
10: 4
22: 2
00: 1
01: 2
11: 0
02: 3
12: 4
failed to invoke constructor: public matrices.MatrixFactorization(com.google.gson.JsonElement) with arguments: [] reason: java.lang.IllegalArgumentException: wrong number of arguments. Stacktrace follows:
Message: failed to invoke constructor: public matrices.MatrixFactorization(com.google.gson.JsonElement) with arguments: [] reason: java.lang.IllegalArgumentException: wrong number of arguments
    Line | Method
->>   15 | create    in turingpages.rest.MFController$$ENuqtska
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|    195 | doFilter  in grails.plugin.cache.web.filter.PageFragmentCachingFilter
|     63 | doFilter  in grails.plugin.cache.web.filter.AbstractFilter
|   1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    603 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^    722 | run       in java.lang.Thread

我对使用 JSON 很陌生。任何帮助表示赞赏。谢谢。

4

1 回答 1

3

1.

默认情况下,jQuery 会将这些数据作为请求参数而不是 JSON 传递。所以你应该构建一个 JSON 字符串来传递给 jQuery。我可以向您推荐JSON 3 库。在这种情况下,它将是:

$.ajax({  
    type: "POST",  
    data: JSON.stringify(matrixArray),  
    url: "/turingpages/factorize/create",
    success: function(data) {
        //USE DATA
    }  
});  

2.

在服务器端,您还可以使用标准 Grails JSON 转换器(但如果您愿意,也可以使用 Gson),请参阅http://grails.org/Converters+Reference

在这种情况下,您可以使用

def create() {
    MatrixFactorization m = new MatrixFactorization(request.JSON)
    render m.answer as JSON
}
于 2013-01-18T08:21:55.627 回答