从数据库中获取信息

时间:2017-09-09 05:53:34

标签: java android

我已设置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")出错。请帮忙。

2 个答案:

答案 0 :(得分:1)

您的回复是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();
}

希望这会对你有所帮助。

答案 1 :(得分:0)

试试这个:

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){
}