android - GET 请求 JSONObject android

标签 android json http get connection

我做了一个简单的 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/

相关文章:

json - 在 Docker 中将 JSON 文件作为环境变量传递

ios - 无法将 JSON 响应分配给预先声明的数组

android - 当我在JSON解析器中添加数据对象时出错

java - 如何将 ArrayList<Class Object> 从 Fragment Intent 到 Activity

android - 谷歌播放服务更新

api - 每 X 分钟向我发送一次 HTTP GET 请求

http - Groovy 中的 Mule HTTP 监听器查询?

android - 如何从谷歌驱动器 url 在 android 中显示视频

json - 从 postgreSQL 中的表查询 json 对象

ruby - 异步运行 Sinatra 服务器和子进程