我的example-ajax调用的Json-Response-Body将不会按预期进行deserilise。出于测试目的,我想返回一个空的JSON-Array。
JavaScript: JSON-Ajax-Call
saveFiles: function (files) {
$.ajax({
url: "SaveFile.do",
type: "post",
data: JSON.stringify(files),
contentType: "application/json",
success: function (saved) {
showSaveResult(saved);
}
});
},
Java-Controller:
@RequestMapping(value="/SaveFile.do", method = RequestMethod.POST)
@ResponseBody public ArrayNode createSaveResult (@RequestBody Data[] entities, BindingResult result, Locale locale){
ArrayNode jsonReturn = new ArrayNode(jsonNodeFactory);
return jsonReturn;
}
Request:
[{key:value1},{key:value2}]
Response:
{"array":true,"elements":[],"containerNode":true,"valueAsText":null,"numberType":null,"fields":[],"fieldNames":[],
"null":false,"textValue":null,"booleanValue":false,"long":false,"valueNode":false,"missingNode":false,
"object":false,"pojo":false,"number":false,"integralNumber":false,"floatingPointNumber":false,"int":false,
"double":false,"bigDecimal":false,"bigInteger":false,"textual":false,"boolean":false,"binary":false,
"numberValue":null,"intValue":0,"longValue":0,"bigIntegerValue":0,"doubleValue":0.0,"decimalValue":0,
"binaryValue":null,"valueAsInt":0,"valueAsLong":0,"valueAsDouble":0.0,"valueAsBoolean":false}
相反,响应提供了完整的ArrayNode对象。我该如何解决这个问题?
答案 0 :(得分:0)
ArrayNode
是杰克逊对阵列中单个元素的表示。如果您只是返回它,那么您将获得ArrayNode
的序列化版本,而不是您想要的空数组元素。
您可以返回代表预期数据集的类:
private static class SaveResult {
String key;
String value;
}
@ResponseBody public SaveResult[] createSaveResult (@RequestBody Data[] entities, BindingResult result, Locale locale){
return new SaveResult[0];
}
你也可以手工建立Json并返回字符串,如下所示(How to create this json string using Jackson?)。
我倾向于第一种方法,因为我觉得快速阅读代码会更加明显。