json转JSONArray 报,net.sf.json.JSONException: A JSONArray text must start with ‘[’ at character
服务器端代码片
.
@RequestMapping("/filmCategotydelete")
public ResultVO filmCategotydelete(@RequestBody String json) throws IOException {
JSONArray jsonArray = JSONArray.fromObject(json);
List<FilmCategory> filmCategoryList = (List<FilmCategory>)jsonArray.toCollection(jsonArray,FilmCategory.class);
filmCategoryService.delete(filmCategoryList);
return ResultVOUtil.success(null);
}
前端代码片`.
$.ajax({
type : "POST",
contentType: "application/json;charset=UTF-8",
url : "http://localhost:8080/film/filmCategotydelete",
// 数据,json字符串
data : "["+ JSON.stringify(data) + "]",
success : function(result) {
layer.msg('已删除');
},
error : function(e){
console.log(e.status);
console.log(e.responseText);
}
});
问题原因
JSONObject是把基础类型的数据变成jon 例如: {name:"wangming",age:18}
JSONArray是把集合或者数组变成json 例如:[{name:"wangming",age:18},{name:"xiaohong",age:17}]
解决方案
方法一:在前端传入数据时在json串前后加上 "["和 "]"
data : "["+ JSON.stringify(data) + "]",
方法二:在后端接受数据后在json串前后加上 "["和 "]"
json = "[" + json + "]"
方法三:把JSONArray换为JSONObject
不推荐方法二和三,因为接受到前端的数据可能是集合json串也可能是单个对象json串。 后端保持一致,前端在单个对象json串,采用方法一最好不过!