当我尝试用IP地址连接web服务器时,我得到了这个JSON错误。
org.json.JSONException: Value {"dsdata":{"ttlogin":[{"BundyId":"9090","Name":"IT DEVELOPMENT"}]}} of type org.json.JSONObject cannot be converted to JSONArray
W/System.err: at org.json.JSON.typeMismatch(JSON.java:112)
My java code
@Override
protected String doInBackground(String... params) {
String login_url ="http://200.200.200.20/bin/dev/dispatch/truckunloading.p";
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("ctype", "UTF-8") + "=" + URLEncoder.encode("login", "UTF-8") + "&"
+ URLEncoder.encode("clogin", "UTF-8") + "=" + URLEncoder.encode("9090", "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
Log.e("ERROR OBJECT", "Conneting");
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream, "iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
try {
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
Log.e("ERROR OBJECT", jsonobject.toString());
}
} catch (JSONException e) {
e.printStackTrace();
return response;
}
return "good";
} catch (MalformedURLException e) {
e.printStackTrace();
return "fail";
} catch (IOException ee) {
ee.printStackTrace();
return "fail";
}
}
我到处找都找不出来。
它在浏览器中给了我理想的响应,但我不知道android有什么问题!
请帮帮我。
JSONArray字符串包含在[]
中,JSONObject字符串包含在{}
中。字符串你试图解析不是JSONArray——JSONObject,而不是
JSONArray jsonarray = new JSONArray(response);
你需要使用
JSONObject jsonObj = new JSONObject(response);
这就是为什么错误信息显示为type org.json.JSONObject cannot be converted to JSONArray
。
一旦有了对象,就可以得到嵌套在in中的对象或数组。在本例中,JSON字符串看起来像这样:
{"dsdata":{"ttlogin":[{"BundyId":"9090","Name":"IT DEVELOPMENT"}]}}
所以如果你想获得"ttlogin"数组,可以使用
JSONObject jsonObj = new JSONObject(response);
JSONArray arr = jsonObj.getJSONObject("dsdata").getJSONArray("ttlogin");