这是我的doInBackground
protected Integer doInBackground(String... args) {
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", Username));
params.add(new BasicNameValuePair("password", Password));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
Log.d("Login attempt", json.toString());
success = json.getInt(TAG_SUCCESS);
res = json.getString(TAG_MESSAGE);
loginposition = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < loginposition.length(); i++) {
JSONObject c = loginposition.getJSONObject(i);
Position = c.getString(TAG_POSITION);
}
} catch (JSONException e) {
Log.e(TAG, "JSON error", e);
success = Integer.valueOf(0);
}
return success;
}
我声明Position变量为String Position
,我不知道为什么我的android json说我的成功不是1或null。。甚至我的标签贴。
这是我的logcat
12-13 15:52:09.830: D/request!(27146): starting
12-13 15:52:13.139: D/Login attempt(27146): {"posts":["user"],"message":"Login Successful!","success":1}
12-13 15:52:13.149: E/(27146): JSON error
12-13 15:52:13.149: E/(27146): org.json.JSONException: Value user at 0 of type java.lang.String cannot be converted to JSONObject
12-13 15:52:13.149: E/(27146): at org.json.JSON.typeMismatch(JSON.java:96)
12-13 15:52:13.149: E/(27146): at org.json.JSONArray.getJSONObject(JSONArray.java:484)
12-13 15:52:13.149: E/(27146): at com.pmss.Login$AttemptLogin.doInBackground(Login.java:157)
12-13 15:52:13.149: E/(27146): at com.pmss.Login$AttemptLogin.doInBackground(Login.java:1)
12-13 15:52:13.149: E/(27146): at android.os.AsyncTask$2.call(AsyncTask.java:185)
12-13 15:52:13.149: E/(27146): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
12-13 15:52:13.149: E/(27146): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
12-13 15:52:13.149: E/(27146): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
12-13 15:52:13.149: E/(27146): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
12-13 15:52:13.149: E/(27146): at java.lang.Thread.run(Thread.java:1019)
12-13 15:52:13.149: D/Login Failure!(27146): res: Login Successful!
您在posts
中得到一个String[]
,并试图将其强制转换为JSONObject
,这会给您带来异常。
尝试更换
JSONObject c = loginposition.getJSONObject(i);
至
String jsonText = loginposition.getString(i);
如果
"loginposition是JSONArray类型yes,Position是一个字符串变量,负责从我的数据库中保存字符串,比如用户和工作人员"
你有这个json:
{"posts":["user"],"message":"Login Successful!","success":1}
你可以这样做:
//loop through all the entries in loginposition and extract strings for each index
for (int i = 0; i < loginposition.length(); i++) {
position = loginposition.getJSONObject(i);
}
如果您的json包含多个用户,例如["user","staff"],则此循环将遍历所有用户,因此您需要相应地处理此问题。
注意:请记住,根据Java惯例,您应该使用第一个字母小写的变量名(因此"position"而不是"position")。