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

}]
5
  • 1
    What don't you understand about JSONObject["pr_num"] is not a JSONArray? Commented Jan 16, 2015 at 19:27
  • So how can i retrieve multiple instances of pr_num from this string? Commented Jan 16, 2015 at 19:30
  • JSONObject obj = new JSONObject(json); is incompatible with the given input. Commented Jan 16, 2015 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. Commented Jan 16, 2015 at 19:36
  • Also, I checked my jsonString with jsonlint.com and it is valid string. Commented Jan 16, 2015 at 19:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
You are welcome. Check it like the following link, stackoverflow.com/questions/18226288/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.