How to Fetch Records from JSON Having the Same Name into Android's java file

StackOverflow https://stackoverflow.com/questions/23671658

  •  23-07-2023
  •  | 
  •  

سؤال

[{"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,

هل كانت مفيدة؟

المحلول 2

[
    {
        "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.

نصائح أخرى

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");
  }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top