我做了一个简单的GET请求,如果我的登录名和密码正确,则返回1或0。我在另一个线程上做连接.
喜欢这个:
public void getConnection(){
String url = null;
url = NOM_HOTE + PATH_METHODE + "identifiant="+ identifiant.getText().toString() + "&password="+ password.getText().toString();
HttpClient httpClient = new DefaultHttpClient();
try{
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
if(httpEntity != null){
InputStream inputStream = httpEntity.getContent();
//Lecture du retour au format JSON
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String ligneLue = bufferedReader.readLine();
while(ligneLue != null){
stringBuilder.append(ligneLue + " n");
ligneLue = bufferedReader.readLine();
}
bufferedReader.close();
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
Log.i("Chaine JSON", stringBuilder.toString());
JSONObject jsonResultSet = jsonObject.getJSONObject("nb"); <--it's here where the error occured
// int nombreDeResultatsTotal = jsonResultSet.getInt("nb");
// Log.i(LOG_TAG, "Resultats retourne" + nombreDeResultatsTotal);
}// <-- end IF
}catch (IOException e){
Log.e(LOG_TAG+ "1", e.getMessage());
}catch (JSONException e){
Log.e(LOG_TAG+ "2", e.getMessage());
}
}
我有一个这样的 JSON 返回:{"nb":"1"}
或{"nb":"0"}
所以我的 JSON 是正确的。但是当我提交表格时,我在catch(JSONException
)上遇到了此错误:
11-07 17:01:57.833: E/ClientJSON2(32530):nb 处的值 1 类型为 java.lang.String,无法转换为 JSONObject
我不明白为什么,虽然我的语法,连接是正确的,并且在带有标签"Chaine JSON"的日志上,我在响应中{"nb:"1"}
。
nb 是一个String
,而不是一个JSONObject
。改变
JSONObject jsonResultSet = jsonObject.getJSONObject("nb");
在
String result = jsonObject.getString("nb");
"nb"表示的值是字符串而不是对象。
使用jsonObject.getString("nb");
即使值是数字jsonObject.getInt("nb");
也可以使用
使用
String myReturnValue = jsonObject. getString("nb");
而不是
JSONObject jsonResultSet = jsonObject.getJSONObject("nb");
这将返回一个字符串;)