GET请求JSONObject android

时间:2013-11-08 08:18:13

标签: 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"} ..

3 个答案:

答案 0 :(得分:5)

nb是String,而不是JSONObject。变化

JSONObject jsonResultSet = jsonObject.getJSONObject("nb");

String result = jsonObject.getString("nb");

答案 1 :(得分:0)

使用

String myReturnValue = jsonObject. getString("nb");

而不是

JSONObject jsonResultSet = jsonObject.getJSONObject("nb");

这将返回一个字符串;)

答案 2 :(得分:0)

由“nb”表示的值是字符串而不是对象。

如果值是数字

,则使用jsonObject.getString("nb");偶数jsonObject.getInt("nb");将起作用