我已经设置了okHttp,以便response.body().string();返回
[{"id":"1","username":"netsgets","password":"test","likedOne":"","likedTwo":"","likedThree":"","likedFour":"","likedFive":""},{"id":"2","username":"test","password":"test","likedOne":"","likedTwo":"","likedThree":"","likedFour":"","likedFive":""},{"id":"3","username":"netsgets2","password":"test","likedOne":"","likedTwo":"","likedThree":"","likedFour":"","likedFive":""}]我想搜索所有用户名,并将它们添加到HashMap中。这就是我所拥有的,但它不工作:
final String TestVar = response.body().string();
for (int data_i = 0; data_i < TestVar.length(); data_i++) {
Log.d("OkHttp","debug3");
HashMap<String, String> hashMap = new HashMap<String, String>();
try {
hashMap.put("username",
TestVar.getString("username"));
} catch (JSONException e) {
e.printStackTrace();
}
usersInfo.add(hashMap);
}
}它不仅不能工作,TestVar.getString("username")还会得到一个错误。请帮帮忙。
发布于 2017-09-09 14:12:14
您的响应是JSONArray,因此您需要解析JSON并获取对象。要从JSON获取对象,可以尝试下面的代码
try {
HashMap<String, String> hashMap = new HashMap<String, String>();
String TestVar = response.body().string();
JSONArray jsonArray = new JSONArray(TestVar);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
hashMap.put("username", jsonObject.getString("username"));
}
}catch (JSONException e) {
e.printStackTrace();
}希望这能对你有所帮助。
发布于 2017-09-09 14:09:42
试试这个:
try{
JSONArray jsonArray = new JSONArray(response.body().string());
for (int data_i = 0; data_i < jsonArray.length(); data_i++) {
HashMap<String, String> hashMap = new HashMap<String, String>();
JSONObject jsonObject = jsonArray.getJSONObject(data_i);
hashMap.put("username",jsonObject.getString("username"));
usersInfo.add(hashMap);
}
}catch(JSONExceptrion e){
}https://stackoverflow.com/questions/46127582
复制相似问题