我做了一个简单的 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): java.lang.String 类型的 nb 处的值 1 无法转换为 JSONObject
我不明白为什么,而我的语法、连接是正确的,并且在带有标签“Chaine JSON”的日志上,我的响应中有 {"nb:"1"}
。
最佳答案
nb 是一个 String
,而不是 JSONObject
。改变
JSONObject jsonResultSet = jsonObject.getJSONObject("nb");
在
String result = jsonObject.getString("nb");
关于android - GET 请求 JSONObject android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19854416/