Abar New
Abar New

Reputation: 27

Get value of array by key

I get JSon from url:

PHP output:

{"error":"true","code":"inValid"}

Android code :

JSONObject jsonRootObject = new JSONObject(result); // result is output php
JSONArray tasks = jsonRootObject.optJSONArray("error");

But not return value of error. I want get TRUE value from ERROR key

Upvotes: 0

Views: 48

Answers (2)

Ratilal Chopda
Ratilal Chopda

Reputation: 4220

Try this

FYI

In general all the JSON nodes will start with a square bracket or with a curly bracket. The difference between [ and { is, the square bracket ([) represents starting of an JSONArray node whereas curly bracket ({) represents JSONObject. So while accessing these nodes we need to call appropriate method to access the data.

JSONObject jsonRootObject = new JSONObject(result);

try 
{
   String strError = jsonRootObject.getString("error");
   String strCode = jsonRootObject.getString("code");

   Log.i("Error",":"+strError);
   Log.i("Code",":"+strCode);
}
catch (JSONException e) 
{
      // TODO Auto-generated catch block
      e.printStackTrace();
}

Upvotes: 1

AbuQauod
AbuQauod

Reputation: 919

have you tried getString:

JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(0);
String mError = jObj.getString("error");

Upvotes: 0

Related Questions