我有从网站获取 json 字符串的代码:
post.setEntity(entity);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
result = EntityUtils.toString(resEntity, HTTP.UTF_8);
这是结果中的 json 示例:
{"status":"0","user_id":"123","name":"test","session_code":"6f33d4ee610651530f04b1f700ebc36d"}
在 jsonlint.com 上验证。我尝试使用解析它
JSONObject jo = new JSONObject(result);
在 android 4 上,代码运行良好,但在早期版本中,它给出了
org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject
当我对 json 字符串进行硬编码而不是使其在线时,它适用于早期版本。当我记录 http 请求输出时,我发现它在每件事上都是相同的,除了会话代码随每个成功请求而变化,但两个会话代码具有相同的长度和格式。
任何人都知道这是什么原因以及如何解决它?
更新:
if (!email.isEmpty() && !password.isEmpty()){
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://www.xxxxxx.com/api/login.php";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("email", email));
postParams.add(new BasicNameValuePair("pass", password));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams, HTTP.UTF_8);
post.setEntity(entity);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
result = EntityUtils.toString(resEntity, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
Log.e(TAG, e.toString());
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
} catch (ParseException e) {
Log.e(TAG, e.toString());
} catch (IOException e) {
Log.e(TAG, e.toString());
}
}
if (result != null) {
try {
JSONObject jo = new JSONObject(result);
switch (jo.getInt("status")) {
case 0 : {
userName = jo.getString("name");
userID = jo.getInt("user_id");
authCode = jo.getString("session_code");
return 0;
}
default:
return jo.getInt("status");
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
}
}