2017-03-08 91 views
-1

我有这样的凌空onResponse:JSONArray不能申请为java.lang.String

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"}] 
+1

你可以分享响应JSON,看起来像“名称”和“图片”值也是JSONArray,而不仅仅是字符串。 – Shubham

+0

@Shubham它是这样的:'[{“name”:“josh”,“picture”:“http:\/\/ip \ /pic.png”}]' –

+3

你不是在循环阵列! –

回答

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(); 
     } 
+0

谢谢你的回答! –

+0

@RickJoe you'er welcome –

1

扩大对@Atef野兔的评论:

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); 
+0

非常感谢你 –

+0

编辑答案,谢谢指出。 – Shubham

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(); 
} 
+0

非常感谢你,朋友。 –

相关问题