Reputation: 758
For one of my web services, I am getting the following response.
"COLUMNS": [
"DIST_ID",
"NAME",
"HOME_PHONE",
"PAID_RANK",
"END_RANK",
"VOL1",
"VOL3"
]
"DATA": {
"DIST_ID": [
3,
1002,
1040,
1290,
1041,
1421,
7200,
5980,
3962,
1070,
9369,
]
}
How can I parse this?
I tried like
JSONArray colArray = response.getJSONArray(COLUMNS);
for(int i=0; i<colArray.length(); i++){
if(Constants.LOG)Log.d("","Column "+colArray.getJSONObject(i).toString());
}
But it didn't worked. It's throwing exception like
09-30 12:51:56.076: W/System.err(3003): org.json.JSONException: Value DIST_ID at 0 of type java.lang.String cannot be converted to JSONObject
09-30 12:51:56.076: W/System.err(3003): at org.json.JSON.typeMismatch(JSON.java:96)
09-30 12:51:56.076: W/System.err(3003): at org.json.JSONArray.getJSONObject(JSONArray.java:484)
09-30 12:51:56.076: W/System.err(3003): at com.vl.infotrax.modules.reports.ReportsEngine.parseReportsDetailsData(ReportsEngine.java:156)
09-30 12:51:56.076: W/System.err(3003): at com.vl.infotrax.modules.reports.ReportsEngine.retrieveReportsDetailsData(ReportsEngine.java:126)
09-30 12:51:56.076: W/System.err(3003): at com.vl.infotrax.modules.reports.ReportsDetailsFragment$GetReportsDetailsData.doInBackground(ReportsDetailsFragment.java:66)
09-30 12:51:56.076: W/System.err(3003): at com.vl.infotrax.modules.reports.ReportsDetailsFragment$GetReportsDetailsData.doInBackground(ReportsDetailsFragment.java:1)
09-30 12:51:56.084: W/System.err(3003): at android.os.AsyncTask$2.call(AsyncTask.java:185)
09-30 12:51:56.084: W/System.err(3003): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-30 12:51:56.084: W/System.err(3003): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-30 12:51:56.084: W/System.err(3003): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
09-30 12:51:56.084: W/System.err(3003): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
09-30 12:51:56.084: W/System.err(3003): at java.lang.Thread.run(Thread.java:1096)
Any one has idea about how to resolve this? Thanks in advance.
Upvotes: 2
Views: 7453
Reputation: 1025
First of all you need to get the JSON string parsed using JSONTokener , please see the sample code given below
String strJSON = ""; // your JSON string goes here
JSONObject jObject = (JSONObject) new JSONTokener(strJSON).nextValue();
JSONArray jAryColumns;
if(jObject.has("Columns")){
jAryColumns = jObject.getJSONArray("Columns");// use the array as you please
}
Use the technique described in above snippet and retrieve the "DATA" JSON object from jObject, from that you could get "DIST_ID".
Upvotes: 0
Reputation: 1477
JSONArray colArray = response.getJSONArray(COLUMNS);
for(int i=0; i<colArray.length(); i++){
Log.d("","Column "+colArray.getString(i));
}
Upvotes: 6
Reputation: 4339
You have to get directly the values as String
and not as JSONObject
.
Upvotes: 0