我在阅读JSON数组时遇到问题,因为在我的数组中,还有另一个数组,我很困惑。请看我的代码。
JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
JSONObject obj = JSONFactoryUtil.createJSONObject();
JSONObject jsonObjectReturn = JSONFactoryUtil.createJSONObject();
//JSONOBJECT RETURN
JSONArray array = JSONFactoryUtil.createJSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
obj = jsonArray.getJSONObject(i);
callableStatement = (CallableStatement) conn
.prepareCall("{call TaxpaymentSPv2(?,?,?,?,?,?,?,?)}");
callableStatement.setString(1, obj.getString("rdoCode"));
callableStatement.setString(2, obj.getString("rcoCode"));
callableStatement.setString(3, obj.getString("tpTin"));
callableStatement.setString(4, obj.getString("tpName"));
callableStatement.setString(5, obj.getString("tpAddress"));
callableStatement.setString(6, obj.getString("receiptType"));
callableStatement.registerOutParameter(7, Types.VARCHAR);
callableStatement.registerOutParameter(8, Types.VARCHAR);
callableStatement.executeUpdate();
String rNo = callableStatement.getString(7);
String date = callableStatement.getString(8);
//---->This is my second Array inside my JSON where im having an error <------
String checkArray = obj.getString("checkArray");
JSONArray jsonArrayCheck = JSONFactoryUtil.createJSONArray(stringArray);
JSONArray jsonArray2 = jsonObject.getJSONArray("checkArray");
System.out.println("..........." + jsonArray2);
jsonObjectReturn = JSONFactoryUtil.createJSONObject();
jsonObjectReturn.put("rNo", rNo);
jsonObjectReturn.put("date", date);
array.put(jsonObjectReturn);
}
return array;
这是我的JSON输入:
{
"dataArray": [{
"rdoCode": "001",
"rcoCode": "002911",
"tpTin": "200746409",
"tpName": "JOHN DOE",
"tpAddress": "LA CALIFORNIA",
"receiptType":"ROR",
"receiptMode":"AUTO",
"manualReceiptNo":"",
"checkArray":[{
"ptchkNumber": 14546,
"ptchkDate": 2014-01-01,
"ptchkAmount": 5332,
"ptchkStatus": ""
}]
}]
}
我无法解析出现此错误的&#34; checkArray&#34; 对象。 com.liferay.portal.kernel.json.JSONException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
。谁能告诉我该怎么做?感谢。
答案 0 :(得分:2)
您需要更改代码:
String checkArray = obj.getString("checkArray");
以下代码:
JSONArray checkArray = obj.getJSONArray("checkArray");
JSONObject checkObj = checkArray.getJSONObject(0);
int ptchkNumber = checkObj.getInt("ptchkNumber");
因为密钥checkArray
是JSON中的数组,所以您不能使用getString()
而是使用getJSONArray()
。
<强>更新强>
要获取数组中的每个对象,您可以迭代并访问每个对象:
JSONArray checkArray = obj.getJSONArray("checkArray");
JSONObject checkObj;
for (int itemIndex=0, totalObject = checkArray.length(); itemIndex < totalObject; itemIndex++) {
checkObj = checkArray.getJSONObject(itemIndex);
int ptchkNumber = checkObj.getInt("ptchkNumber");
}