0

I have a JSON String that I am parsing, and I want to retrieve the value of the field "pr_num". I am getting this error:

JSONObject["pr_num"] is not a JSONArray.

My code is below:

JSONObject obj = new JSONObject(jsonString);

JSONArray data = obj.getJSONArray("pr_num");
JSONObject obj1= data.getJSONObject(0);
System.out.println("JSON CONTENTS ARE"+obj1.getString("pr_num"));

I want to get values for pr_num field which are 690052 and null.

jsonString is mention below

[{
    "executed_by": "vishnuc",
    "testplan_id": 17372,
    "pr_num": "690052"
},
{
    "executed_by": "kkavitha",
    "testplan_id": 17372,
    "pr_num": null

}]
Ammad
  • 4,031
  • 12
  • 39
  • 62
  • 1
    What don't you understand about `JSONObject["pr_num"] is not a JSONArray`? – Sotirios Delimanolis Jan 16 '15 at 19:27
  • So how can i retrieve multiple instances of pr_num from this string? – Ammad Jan 16 '15 at 19:30
  • `JSONObject obj = new JSONObject(json);` is incompatible with the given input. – njzk2 Jan 16 '15 at 19:32
  • json is String which is equal to [{ "executed_by": "vishnuc", "testplan_id": 17372, "pr_num": "690052", }, { "executed_by": "kkavitha", "testplan_id": 17372, "pr_num": null, }] ---- The same one i have already posted above. – Ammad Jan 16 '15 at 19:36
  • Also, I checked my jsonString with http://jsonlint.com/ and it is valid string. – Ammad Jan 16 '15 at 19:50

1 Answers1

1

your jsonString is a json formatted array So first you have to get it to a json array (not to an json object)

JSONArray obj = new JSONArray(jsonString);

Now you can iterate through the obj array

for(int i=0;i<obj.length();i++){
 System.out.println("content one: " + obj.getJSONObject(i).getString("pr_num"));
}

Hope this helps.

Ramindu De Silva
  • 194
  • 4
  • 13
  • Thanks, I am able to retrieve value. one issue is if the value of field pr_num is null i am getting this error, JSONObject["pr_num"] not a string. if i put it under try, catch block it is working fine. Any other graceful way for handling null values for pr_num field? – Ammad Jan 16 '15 at 21:48
  • You are welcome. Check it like the following link, http://stackoverflow.com/questions/18226288/json-jsonobject-optstring-returns-string-null – Ramindu De Silva Jan 17 '15 at 02:21