【问题标题】:org.json.JSONException: Value Data of type java.lang.String cannot be converted to JSONObjectorg.json.JSONException:java.lang.String 类型的值数据无法转换为 JSONObject
【发布时间】:2017-07-21 11:59:02
【问题描述】:

这是我的 Android 代码:

 public void SendDataToServer(final String name, final String email, final String password){
        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... params) {

                String QuickName = name ;
                String QuickEmail = email ;
                String QuickPassword = password;


                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                nameValuePairs.add(new BasicNameValuePair("nome", QuickName));
                nameValuePairs.add(new BasicNameValuePair("email", QuickEmail));
                nameValuePairs.add(new BasicNameValuePair("password", QuickPassword));


                try {
                    HttpClient httpClient = new DefaultHttpClient();

                    HttpPost httpPost = new HttpPost(Configs.signup);

                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpClient.execute(httpPost);

                    HttpEntity entity = response.getEntity();


                } catch (ClientProtocolException e) {

                } catch (IOException e) {

                }
                return "Data Submit Successfully";
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);


                Log.d(result, "Value");


                try {

                    JSONObject jo = new JSONObject(result);
                    String status = jo.optString("status");


                        if (status.equals("0")) {
                            Toast.makeText(Signup.this, "Username already exists", Toast.LENGTH_LONG).show();

                        } else if (status.equals("1")) {
                            Intent intent = new Intent(Signup.this, Login.class);
                            startActivity(intent);

                            Toast.makeText(Signup.this, "Registered successfully", Toast.LENGTH_LONG).show();
                            Toast.makeText(Signup.this, "Verify your email adress in email received", Toast.LENGTH_SHORT).show();
                            finish();
                        } else if (status.equals("2")) {
                            Toast.makeText(Signup.this, "Failed to Signup", Toast.LENGTH_LONG).show();
                        }
                        //}

                }catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }
        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute(name, email, password);
    }

这是错误:

07-21 12:55:35.297 24973-24973/com.futegolo.igomessenger W/System.err: org.json.JSONException:java.lang.String 类型的值数据不能 转换为 JSONObject

这是我的 json 响应

{"status":0}

【问题讨论】:

    标签: java android json


    【解决方案1】:

    这是因为您没有在 doInBackground() 方法中从服务返回实际响应。你以

    身份返回
     return "Data Submit Successfully"
    

    当您在 onPostExecute() 方法中转换该字符串时,显然这不是有效的 JsonObject

    在“HttpEntity entity = response.getEntity();”之后替换您的代码

    HttpEntity entity = response.getEntity();
    String result = null;
        if (entity != null) {
    
            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            result= convertStreamToString(instream);
            // now you have the string representation of the HTML request
            instream.close();
        }
    
        private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    
    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
    

    }

    而是返回您的硬编码字符串返回结果。希望有帮助。 如需进一步参考,您可以点击以下链接

    https://stackoverflow.com/questions/4457492/how-do-i-use-the-simple-http-client-in-android
    

    【讨论】:

      【解决方案2】:

      使用如下代码:

         public void SendDataToServer(final String name, final String email, final String password){
                  class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
                      @Override
                      protected String doInBackground(String... params) {
      
                          String QuickName = name ;
                          String QuickEmail = email ;
                          String QuickPassword = password;
      
      
                          List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
      
                          nameValuePairs.add(new BasicNameValuePair("nome", QuickName));
                          nameValuePairs.add(new BasicNameValuePair("email", QuickEmail));
                          nameValuePairs.add(new BasicNameValuePair("password", QuickPassword));
      
      
                          try {
                              HttpClient httpClient = new DefaultHttpClient();
      
                              HttpPost httpPost = new HttpPost(Configs.signup);
      
                              httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      
                              HttpResponse response = httpClient.execute(httpPost);
      
                              HttpEntity entity = response.getEntity();
          StringBuffer result= new StringBuffer();
           BufferedReader in = new BufferedReader(
                              new InputStreamReader(entity.getContent()));
                      String inputLine;
                      while ((inputLine = in.readLine()) != null) {
                          result.append(inputLine);
                      }
                      in.close();
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
                  return result.toString();
                      }
      
                      @Override
                      protected void onPostExecute(String result) {
                          super.onPostExecute(result);
      
      
                          Log.d(result, "Value");
      
      
                          try {
      
                              JSONObject jo = new JSONObject(result);
                              String status = jo.optString("status");
      
      
                                  if (status.equals("0")) {
                                      Toast.makeText(Signup.this, "Username already exists", Toast.LENGTH_LONG).show();
      
                                  } else if (status.equals("1")) {
                                      Intent intent = new Intent(Signup.this, Login.class);
                                      startActivity(intent);
      
                                      Toast.makeText(Signup.this, "Registered successfully", Toast.LENGTH_LONG).show();
                                      Toast.makeText(Signup.this, "Verify your email adress in email received", Toast.LENGTH_SHORT).show();
                                      finish();
                                  } else if (status.equals("2")) {
                                      Toast.makeText(Signup.this, "Failed to Signup", Toast.LENGTH_LONG).show();
                                  }
                                  //}
      
                          }catch (JSONException e) {
                              e.printStackTrace();
                          }
      
                      }
                  }
                  SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
                  sendPostReqAsyncTask.execute(name, email, password);
              }
      

      【讨论】:

        【解决方案3】:

        Appache 已经为 EntityUtils 提供了一个 Util 类。

        用此代码替换return "Data Submit Successfully"

        String responseText = EntityUtils.toString(httpResponse.getEntity());
        EntityUtils.consume(httpResponse.getEntity());
        
        return responseText;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多