[{"UserID":"vishi"},{"UserID":"vish"}]
这是我从 php 发送的 json 数据......我怎样才能在 android 中获得这些具有相同名称的值谢谢,
[{"UserID":"vishi"},{"UserID":"vish"}]
这是我从 php 发送的 json 数据......我怎样才能在 android 中获得这些具有相同名称的值谢谢,
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");
}
}
[
{
"UserID": "vishi" // key is UserId. value is vishi
},
{
"UserID": "vish"
}
]
关键UserID
是一样的。只需遍历数组并获取值
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);
}
笔记:
Blackbelt 的答案也将起作用,它也有 null 检查原因optJSONObject()
也可能返回 null。这是一个更好的方法
借鉴黑带的答案
JSONObject obj = array.optJSONObject(i);
if (obj != null) {
String userId = obj.optString("UserID");
}
从文档
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.