获取错误时,JSONArray [0]不是JSONObject,而是从JSON数组中获取对象(Java代码行#5)。
客户端jQuery
function setCosting(){
var costingArray = {};
costingArray = getCostingArray();
var costingData = JSON.stringify(costingArray);
alert(costingData);
$.ajax({
type:"POST",
url:"/costApp/budgetline.do?action=setCosting",
data:{"costingData": costingData},
datatype:'json',
success: function (msg) {
if (msg) {
alert('success');
}
},
error: function (msg) {
alert('error');
}
});
function getCostingArray() {
var rows = $("table tbody tr");
var dataset = [];
rows.each(function(i, row){
var rowset = {};
var $row = $(row);
rowset['travelType'] = $row.find('#travelType').val();
rowset['staff'] = $row.find('#staff').val();
rowset['trip'] = $row.find('#trip').val();
dataset.push(rowset);
});
return dataset;
}
$('#save').click(function() {
setCosting();
});
Java代码
Map mpVal = request.getParameterMap();
JSONObject rootObj = new JSONObject(mpVal);
JSONArray arrayObj = rootObj.getJSONArray("costingData");
for(int m=0; m<arrayObj.length(); m++){
**JSONObject costing = arrayObj.getJSONObject(m);**
System.out.println(costing.getInt("travelType"));
System.out.println(costing.getInt("staff"));
System.out.println(costing.getInt("trip"));
}
数组包含一个值为:
的sigle元素[
{
"travelType": "1",
"staff": "red",
"trip": ""
},
{
"travelType": "2",
"staff": "blue",
"trip": ""
},
{
"travelType": "3",
"staff": "green",
"trip": ""
}
]
任何评论都将不胜感激。
答案 0 :(得分:1)
因为,数组包含一个元素,其值为数组本身,所以需要
JSONArray arrayObj = rootObj.getJSONArray("costingData").getJSONArray(0);
for(int m=0; m<arrayObj.length(); m++){
JSONObject costing = arrayObj.getJSONObject(m);
System.out.println(costing.getString("travelType"));
System.out.println(costing.getString("staff"));
System.out.println(costing.getString("trip"));
}
而且,由于staff
和trip
是字符串,因此您需要使用getString()
代替getInt()
。