gpt4 book ai didi

java - 如何摆脱错误: JSONArray[0] is not a JSONObject

转载 作者:行者123 更新时间:2023-12-01 14:02:01 25 4
gpt4 key购买 nike

从 JSON 数组获取对象时出现错误,JSONArray[0] 不是 JSONObject(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"));
}

该数组包含一个值为:

的元素
[
{
"travelType": "1",
"staff": "red",
"trip": ""
},
{
"travelType": "2",
"staff": "blue",
"trip": ""
},
{
"travelType": "3",
"staff": "green",
"trip": ""
}
]

如有任何评论,我们将不胜感激。

最佳答案

由于该数组包含一个元素,其值本身就是一个数组,因此您需要

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"));
}

并且,由于 stafftrip 是字符串,因此您需要使用 getString() 而不是 getInt() >.

关于java - 如何摆脱错误: JSONArray[0] is not a JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19280992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com