Ammad
Ammad

Reputation: 4235

Retrieving null and non null string value from JSON String

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

}]

Upvotes: 0

Views: 1870

Answers (1)

Ramindu De Silva
Ramindu De Silva

Reputation: 3

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.

Upvotes: 1

Related Questions