chiradee chiradee - 1 year ago 149
Java Question

Reading a JSON Array in JAVA

I'm having a problem reading JSON Array because inside my array, there's another array and I'm confused.Please see my code.

JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
JSONObject obj = JSONFactoryUtil.createJSONObject();
JSONObject jsonObjectReturn = JSONFactoryUtil.createJSONObject();

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


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

return array;

Here's my JSON input:

"dataArray": [{

"rdoCode": "001",
"rcoCode": "002911",
"tpTin": "200746409",
"tpName": "JOHN DOE",
"tpAddress": "LA CALIFORNIA",
"ptchkNumber": 14546,
"ptchkDate": 2014-01-01,
"ptchkAmount": 5332,
"ptchkStatus": ""

I can't parse the "checkArray" object that gives me this error.
com.liferay.portal.kernel.json.JSONException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
. Can someone tell me what to do? Thanks.

Answer Source

You need to change code:

String checkArray = obj.getString("checkArray");

to following code:

JSONArray checkArray = obj.getJSONArray("checkArray");
JSONObject checkObj = checkArray.getJSONObject(0);
int ptchkNumber = checkObj.getInt("ptchkNumber");

because key checkArray is array inside JSON, so you cannot using getString() but getJSONArray() instead.


To get each object inside array, you can iterate and access each object:

JSONArray checkArray = obj.getJSONArray("checkArray");
for (int itemIndex=0, totalObject = checkArray.length(); itemIndex < totalObject; itemIndex++) {     
    JSONObject checkObj = checkArray.getJSONObject(itemIndex);
    int ptchkNumber = checkObj.getInt("ptchkNumber");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download