我已经搜索了很多类型的解决方案,但我仍然不知道如何更改它并解决我的错误。我需要有人帮忙,因为我在android中很新。
org.json.JSONException: Value {"user_info":[{"MemberID":"1","Name":"Joshua","Url":"joshua@gmail.com"},{"MemberID":"2","Name":"Mary","Url":"mary@gmail.com"}]} of type org.json.JSONObject cannot be converted to JSONArray
以下是我的变量和解析JSON文件的代码:
公共类MainActivity扩展了Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
TextView id = (TextView) findViewById(R.id.id);
TextView name = (TextView) findViewById(R.id.name);
TextView url = (TextView) findViewById(R.id.url);
JSONObject json = null;
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost user_info = new HttpPost("http://192.168.1.103/ViewList/getJSON.php");
try {
response = myClient.execute(user_info);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
json = jArray.getJSONObject(0);
id.setText(json.getString("MemberID"));
name.setText(json.getString("Name"));
url.setText(json.getString("Url"));
} catch ( JSONException e) {
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
答案 0 :(得分:0)
您的问题是,您正在为JSONArray
对象提供以JSONObject
开头的字符串。课程JSONObject
还有一个方法getJSONArray
,你应该使用它:
JSONObject jObject = new JSONObject(str);
JSONArray jArray = jObject.getJSONArray("user_info");
然后,您可以循环jArray
。
答案 1 :(得分:0)
更改您的代码,首先将实际的JSON
字符串读为JSONOBject
,然后将密钥"user_info"
作为JSONArray
阅读。以下是更改:
try{
JSONObject jsonObject = new JSONObject(str);
//then here you read user_info as array
JSONArray jArray = jsonObject.getJSONArray("user_info");
json = jArray.getJSONObject(0);
id.setText(json.getString("MemberID"));
name.setText(json.getString("Name"));
url.setText(json.getString("Url"));
} catch ( JSONException e) {
e.printStackTrace();
}
尝试一下,让我们知道它是否能解决您的问题。