我已经设置了 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")
还会出错。请帮忙。
最佳答案
您的响应是 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();
}
希望这对您有帮助。
关于java - 从数据库获取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46127582/