我正在尝试将Json数组传递给Grails控制器,然后传递给Java类。我无法弄清楚如何正确地将我的参数传递给Java类。这是相关代码。
AJAX POST:
$('#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
}
...
MatrixFactorization构造函数:
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的新手。任何帮助表示赞赏。感谢。
答案 0 :(得分:3)
1
默认情况下,jQuery会将此数据作为请求参数传递,而不是JSON。所以你应该构建一个JSON字符串来传递给jQuery。我可以推荐你JSON 3 library。在这种情况下,它将是:
$.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
}