Sean
Sean

Reputation: 963

How to get the first value of a JSONArray?

My JSON code is as follows:

returnString = "";          
        JSONArray jArray = new JSONArray(result);
        for(int i=0;i<jArray.length();i++){
            JSONObject json_data = jArray.getJSONObject(i);
            JSONObject c = json_data.getJSONObject("data");
            Log.i("log_tag","statues: "+c.getString("statues"));                
            returnString = c.getString("statues"); }

Now I want to see the values within my JSONArray. The value for statues is either 0 or 1. Further, I will use them in an if else phrase.

What I mean is something like this:

if(value of statues = 0){
do something}
else{
do something else}

How would I do that?

Upvotes: 1

Views: 6660

Answers (1)

Coderji
Coderji

Reputation: 7765

If you want only first status value in the JSONArray

to get the first value from JSONArray simply do outside of the loop and before the if statement:

JSONObject FirstArray = jArray.getJSONObject(0); // first Array in JSONArray
JSONObject data = FirstData.getString("data");
String FirstStatusValue = data.getString("Status");

then parse FirstStatusValue to int and use it in if.

I hope I understood your question well, if I didnt please correct me

if you want all status value within the JSONArray

before the for loop declare an array of string to and add all the status value in it then loop:

String[] StatusArray = new String[jArray.length()]; // will make the status array has the same length as the JSONArray
for(int i=0;i<jArray.length();i++){
        JSONObject json_data = jArray.getJSONObject(i);
        JSONObject c = json_data.getJSONObject("data");
        Log.i("log_tag","statues: "+c.getString("statues"));
        StatusArray[i] = c.getString("status");
        }

then for if statement add for loop then check the statement like:

for (int i = 0; i < StatusArray.length(); i++)
{
   if (StatusArray[i] == 0)
      // do something
   else
      // do something

 }

Upvotes: 2

Related Questions