JSONArray不能应用于java.lang.string

时间:2017-03-08 20:47:49

标签: android android-json

我有这个凌空响应:

 public void onResponse(String response) {
    try {
        JSONArray info = new JSONArray(response);

        String name = info.getString("name");
        String picture = info.getString("picture");
        Picasso.with(context).load(picture).into(profile);
        user_name.setText(name);


    } catch (JSONException e) {
        e.printStackTrace();
        Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
    }

}

问题是("name")("picture")给了我JSONArray不能应用于java.lang.string。

我错过了什么?

编辑:

[{"name":"josh","picture":"http:\/\/192.168.0.11\/pic.png"}]

3 个答案:

答案 0 :(得分:2)

这样做是为了解析这个回复!

  try {
            JSONArray info = new JSONArray(response);

            for (int i =0; i<info.length() ; i++) {
                JSONObject obj = info.getJSONObject(i);
                String name = obj.getString("name");
                String picture = obj.getString("picture");
                Picasso.with(context).load(picture).into(profile);
                user_name.setText(name);
            }


        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }

答案 1 :(得分:1)

扩大@Atef Hares的评论:

JSONArray info = new JSONArray(response);

String name = info.getJSONObject(0).getString("name");
String picture = info.getJSONObject(0).getString("picture");
Picasso.with(context).load(picture).into(profile);
user_name.setText(name);

答案 2 :(得分:1)

更改为以下代码。

try {
    JSONArray info = new JSONArray(response);

    String name = info.getJSONObject(0).getString("name");
    String picture = info.getJSONObject(0).getString("picture");
    Picasso.with(context).load(picture).into(profile);
    user_name.setText(name);


} catch (JSONException e) {
    e.printStackTrace();
    Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}