从服务器发送字符串响应时,java.lang.Integer无法转换为JSONObject

时间:2018-01-29 08:47:35

标签: php android codeigniter

我通过genAsync库从android应用程序向服务器发送数据。在服务器上我插入并检查用户是否已经同时存在。如果用户已经存在而不是我发送json_encoded数组,如果用户不存在,则发送消息即用户已成功插入但是当我发送时消息到应用程序它给出了一个错误 java.lang.Integer无法转换为JSONObject

我还附加了php代码,android代码和错误日志。

php code

class Users extends CI_Controller
{

  public function create(){

    $data=$this->check_exist($this->input->post('user_id'));
    if($data=='0')
    {

        $this->load->model('UsersModel');
        $msg = $this->UsersModel->create();
        if ($msg==true) {
            echo 'user inserted successfully';
        } else {
            echo '0';
        }
    }
    else{
        $data["user_details"]=$data;
        echo json_encode($data);
    }
  }
  public function check_exist($user_id)
    {
      $this->load->helper('url');
      $this->load->model('UsersModel');
      $data=$this->UsersModel->user_exist($user_id);
      if(!empty($data))
      {
        return($data);
      }
      else
      {
        return '0';
      }
   }
}

将数据发送到服务器端的android代码

try {
           final Database_Helper dg = new Database_Helper(getBaseContext());
           ServerUrl obj =new ServerUrl();
           HashMap postData = new HashMap();
           postData.put("user_id",personId);
           postData.put("user_name",personName);
           postData.put("email",personEmail);              
           postData.put("profile_picture",String.valueOf(personPhoto));
           final PostResponseAsyncTask readTask = new PostResponseAsyncTask(UserLogin.this, postData, new AsyncResponse() 
              {

                public void processFinish(String mStringArray) 
                  {
                     Log.w("data", mStringArray.toString());
                     try {
                           JSONObject json= null;
                           json = new JSONObject(mStringArray);
                           JSONArray jsonscoresarray=json.getJSONArray("user_details");
                           final JSONObject details = jsonscoresarray.getJSONObject(0);
                          if (jsonscoresarray.length() == 0) 
                          {
                            //storing data to sqlite if user not exist
                            dg.user_Putrecord(dg, personId, personName, personEmail, String.valueOf(personPhoto));
                          }
                          else
                          {
                             //storing data to sqlite if user exist
          dg.user_Putrecord(dg,details.getString("auth_id"),details.getString("full_name"),details.getString("email_id"),details.getString("profile_url"));
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    Toast.makeText(UserLogin.this, mStringArray.toString(), Toast.LENGTH_LONG).show();
                                }

                            });
                            obj.url("Users","create");
                            readTask.execute(obj.domain_url);
                        }
                        catch (Exception ex)
                        {
                         Toast.makeText(UserLogin.this, ex.getMessage().toString(), Toast.LENGTH_SHORT).show();
                        }

这是我的错误logcat

01-29 13:49:33.765 4455-4455/com.example.ali.ansofexperts W/System.err: org.json.JSONException: Value 1 of type java.lang.Integer cannot be converted to JSONObject
01-29 13:49:33.765 4455-4455/com.example.ali.ansofexperts W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
01-29 13:49:33.765 4455-4455/com.example.ali.ansofexperts W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:160)
01-29 13:49:33.765 4455-4455/com.example.ali.ansofexperts W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
01-29 13:49:33.765 4455-4455/com.example.ali.ansofexperts W/System.err:     at com.example.ali.ansofexperts.UserLogin$4$1.processFinish(UserLogin.java:121)
01-29 13:49:33.765 4455-4455/com.example.ali.ansofexperts W/System.err:     at com.kosalgeek.asynctask.PostResponseAsyncTask.onPostExecute(PostResponseAsyncTask.java:248)
01-29 13:49:33.765 4455-4455/com.example.ali.ansofexperts W/System.err:     at com.kosalgeek.asynctask.PostResponseAsyncTask.onPostExecute(PostResponseAsyncTask.java:31)
01-29 13:49:33.766 4455-4455/com.example.ali.ansofexperts W/System.err:     at android.os.AsyncTask.finish(AsyncTask.java:667)
01-29 13:49:33.766 4455-4455/com.example.ali.ansofexperts W/System.err:     at android.os.AsyncTask.-wrap1(AsyncTask.java)
01-29 13:49:33.766 4455-4455/com.example.ali.ansofexperts W/System.err:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
01-29 13:49:33.766 4455-4455/com.example.ali.ansofexperts W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
01-29 13:49:33.766 4455-4455/com.example.ali.ansofexperts W/System.err:     at android.os.Looper.loop(Looper.java:154)
01-29 13:49:33.766 4455-4455/com.example.ali.ansofexperts W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6121)
01-29 13:49:33.766 4455-4455/com.example.ali.ansofexperts W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
01-29 13:49:33.766 4455-4455/com.example.ali.ansofexperts W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
01-29 13:49:33.766 4455-4455/com.example.ali.ansofexperts W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

我只是想知道当从服务器发出字符串响应时如何处理此异常。

3 个答案:

答案 0 :(得分:1)

我正在为初学者发布完整答案。

我的PHP代码稍有变化,因为我在下面写

public function create(){
    $this->load->model('UsersModel');
    $data=$this->UsersModel->check_exist($this->input->post('user_id'));
    if($data==0){
        $nData=$this->UsersModel->create();
        if($nData!="0"){
        $data=$this->UsersModel->check_exist($this->input->post('user_id'));
            echo json_encode($data);        
        }else{
            die("0");
        }

    }else{
            $result["user_details"]=$data;
            echo json_encode($result);
    }

}

你可以看到我刚从Controller中删除了check_exist函数。因为 在你的控制器中不需要这个功能。

所以我直接从模型中调用它以减少代码行数。

现在android端编码更改

   try {
          final Database_Helper dg = new Database_Helper(getBaseContext());
             ServerUrl obj =new ServerUrl();
             HashMap postData = new HashMap();
             postData.put("user_id",personId);
             postData.put("user_name",personName);
             postData.put("email",personEmail);

             postData.put("profile_picture",String.valueOf(personPhoto));
             final PostResponseAsyncTask readTask = new PostResponseAsyncTask(UserLogin.this, postData, new AsyncResponse() 
              {               
               public void processFinish(String mStringArray) 
               {
                 Log.d("data", mStringArray);
                 if(mStringArray.equals("0"))
                 {
                  Toast.makeText(UserLogin.this, "Invalid login try again", Toast.LENGTH_LONG).show();

                 }
                 else 
                 {
                 try {
                      JSONObject json = null;
                      json = new JSONObject(mStringArray);
                      JSONArray jsonscoresarray = json.getJSONArray("user_details");
                       final JSONObject details = jsonscoresarray.getJSONObject(0);
                       if (mStringArray.equals("0")) 
                       {                      
                         Toast.makeText(UserLogin.this, "At if", Toast.LENGTH_LONG).show();
                       } 
                       else 
                       {                      
                        Toast.makeText(UserLogin.this, "At else", Toast.LENGTH_LONG).show();
                      }
                      Toast.makeText(UserLogin.this, "Login Success", Toast.LENGTH_LONG).show();

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

           }

        });
       obj.url("Users","create");
       readTask.execute(obj.domain_url);
    }
    catch (Exception ex)
    {
      Toast.makeText(UserLogin.this, ex.getMessage().toString(), Toast.LENGTH_SHORT).show();
    }

希望这会对你有所帮助。

答案 1 :(得分:0)

如果用户不存在,则您的方法返回整数0。然后你试图为它添加一个数组索引。

尝试分离您的结果和数据数组:

$exists = $this->check_exist($this->input->post('user_id'));

$result = [];

if(!$exists) {
    // code from above
} else {
    $result["user_details"]=$data;
    echo json_encode($result);
}

将数组索引应用于整数应该引发警告:

https://3v4l.org/9qU7r

答案 2 :(得分:0)

您可能无法使用key = "user_details"

获取数据

在使用之前进行密钥检查,例如:

if(json.has("user_details")) {
    JSONArray jsonscoresarray=json.getJSONArray("user_details");

    ... other code here ...

} else {
    Toast.makeText(UserLogin.this, json.toString(), Toast.LENGTH_LONG).show();
}

修改

问题在于

json = new JSONObject(mStringArray);

,也许你得到了0的响应,因为它不是任何jsonObject,你得到的异常无法将Integer转换为JsonObject

使用下面的代码检查它是否是有效的json,然后相应地处理:

public boolean isJSONValid(String myString) {
    try {
        new JSONObject(myString);
    } catch (JSONException ex) {
        // e.g. in case JSONArray is valid as well...
        try {
            new JSONArray(myString);
        } catch (JSONException ex1) {
            return false;
        }
    }
    return true;
}

现在在您的代码中使用:

if(isValidJson(mStringArray)) {
    JSONObject json = new JSONObject(mStringArray);
    JSONArray jsonscoresarray=json.getJSONArray("user_details");

    ... other code here ...

} else {
    // Response Not Json
    Toast.makeText(UserLogin.this, json.toString(), Toast.LENGTH_LONG).show();
}