문제

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