0
[{"UserID":"vishi"},{"UserID":"vish"}] 

this is the json data that I am sending from php... how can i get these values with same name in android Thanks,

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
Vishvas
  • 5
  • 4

2 Answers2

3
JSONArray array = new JSONArray(...);
int length = array.length() ;
for (int i = 0; i < length; i++) {
  JSONObject obj = array.optJSONObject(i);
  if (obj != null) {
      String userId = obj.optString("UserID");
  }
}
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
1
[
    {
        "UserID": "vishi" // key is UserId. value is vishi
    },
    {
        "UserID": "vish"
    }
]

The key UserID is the same. Just loop through the array and get the value

ArrayList<String> list = new ArrayList<String>();
JSONArray jr = new JSONArray("your json");
for(int i=0i<jr.length();i++)
{
   JSONObject jb = jr.getJSONObject(i);
   String value= jb.getString("UserID");
   list.add(value);
}

Note:

Blackbelt's answer will also work and it also has null check cause optJSONObject() could return null also. This is a better way

Drawing from blackbelt's answer

 JSONObject obj = array.optJSONObject(i);
 if (obj != null) {
  String userId = obj.optString("UserID");
 }

From the docs

public JSONObject optJSONObject (String name)

Added in API level 1
Returns the value mapped by name if it exists and is a JSONObject. Returns null otherwise.
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • Thank you Sir, its working fine but only the second value is getting assigned to the String... how to i get both these values... like can i use some arrays so that i populate the array value[0]="vishi" and value[1]="vish"... please help ... thank you in advance – Vishvas May 15 '14 at 08:18
  • @user3639643 everytime it assings the value to string value. You can add it a arraylist – Raghunandan May 15 '14 at 08:19
  • @user3639643 check the edit. now list has all the items and can be got using `list.get(i).toString()` – Raghunandan May 15 '14 at 08:22
  • @Vishvas no problem you have every right to accept the most efficient answer that worked for you. Blackbelts answer has null check also coz this `optJSONObject(i)` could return null. This also works. I just wanted to know why the uneccpet now. – Raghunandan May 20 '14 at 18:07