无法从Android中的Json获得正确的响应

时间:2015-09-01 07:10:39

标签: php android json

我正在建立一个我一直在与PHP脚本交互的系统。 php脚本用于向mysqli数据库添加记录。我正面临着用android响应Json的问题。 这是我的安卓代码。

inputStream = httpURLConnection.getInputStream();
        bufferedReader= new BufferedReader(new InputStreamReader(inputStream));
        String temp;// = null;
        StringBuilder stringBuilder  = new StringBuilder();
        while((temp = bufferedReader.readLine())!=null) {
            stringBuilder.append(temp);
        }
        String jsonbuilded = stringBuilder.toString();
        Log.i("jsonbuilded string: ",jsonbuilded);
        JSONObject recievedJsonObject = new JSONObject(jsonbuilded);//Line number 114
        String recievedString = recievedJsonObject.getString("result");
            Log.i("String Recieved",recievedString);
        if(recievedString.compareTo("1")==0){
            runOnthisUIThread("Your query has been successfully placed.");
        }
        else if(recievedString.compareTo("2")==0){
            runOnthisUIThread("The payment of Client "+ params[1] + " is already done by "+params[2]);
        }
        else if(recievedString.compareTo("5")==0){
            Log.i("Entry: ",params[0]);
            runOnthisUIThread("Records not found. Please try again later.");
        }
        else if(recievedString.compareTo("4")==0){
            String employ_assoc = recievedJsonObject.getString("name");
            runOnthisUIThread("The payment is already done by "+ employ_assoc);
        }
        else{
            runOnthisUIThread("Unknown Runtime Error... Kindly contact the Developers.");

        }

runOnthisUIThread()是一个显示Toast的功能。

这是我在php中的相关代码片段。

if ($query->num_rows >0)
{
  $query_result = $query->fetch_assoc();
  $id = $query_result['ID'];
  if(!$this->con)
  {
    $resultOfQuery['result'] = '0'; //connection not successfully
    die(json_encode(resultOfQuery));
  }
  else
  {
    $queryforcalc = "SELECT * FROM `".$clientid."` ORDER BY id DESC LIMIT 1";
    $queryforcalcresult = $this->con_user->query($queryforcalc);
    if($queryforcalcresult->num_rows >0)
    {
      $query_calc_rawdata = $queryforcalcresult->fetch_assoc();
      //echo $query_calc_rawdata;
      //This section is for calculation of meter readings.
      $lastmeterreadings = $query_calc_rawdata['meter_readings'];
      $meter_readings = $meter_readings - $lastmeterreadings;
    }
        if($meter_readings > 0)
        {
          $timestamp = $this->string->getCurrentTimeStamp();
          $update_user_table = "INSERT INTO `".DATABASE_USER."`.`$clientid` (`timestamp`, `meter_readings`) VALUES ('$timestamp', '$meter_readings');";
          $this->con_user->query($update_user_table);
          //echo $this->con_user->query($update_user_table);
          //echo $this->con->query($update_query);
          $update_query = "UPDATE `".DATABASE."`.`client_list` SET `Meter_readings` = '$meter_readings', `bool` = '1', `Employ_Assoc` = '$employid' WHERE `client_list`.`ID` = '$clientid';";
          //echo $update_query;
          $this->con->query($update_query);
          //echo $this->con;
          $resultOfQuery['result'] = '1'; // successfully placed
          die(json_encode($resultOfQuery));
        }
        else
        {
          $resultOfQuery['result'] = '2';// Invalid entry of meter readings
          die(json_encode($resultOfQuery));
        }

      }
  }
else
{
  $query_statment = "SELECT * FROM client_list WHERE ID = '{$clientid}' AND bool = '1'";
  $queryresultofsecondphase = $this->con->query($query_statment);
  if($queryresultofsecondphase->num_rows >0)
  {
    $queryResult = $queryresultofsecondphase->fetch_assoc();
    $employname = $queryResult['Employ_Assoc'];
    echo $employname;
    $resultOfQuery['result'] = '4';//Record already excists.
    $resultOfQuery['name'] = $employname;
    die(json_encode($resultOfQuery));
  }
  else
  {
    $resultOfQuery['result']= '5';//Record not found. The user does not excists.
    die(json_encode($resultOfQuery));
  }
}
}

当我返回回复' 4'时,我也必须发送该名称。因此我使用另一个Json标记' name'。但是我得到了一个Json例外。这是我的堆栈跟踪。

09-01 12:18:14.097  25321-25357/com.ems.employ I/connection successful﹕ [ 09-01 12:18:14.102 25321:25357 I/jsonbuilded string:  ]
0{"result":"4","name":"0"}
09-01 12:18:14.102  25321-25357/com.ems.employ W/System.err﹕ org.json.JSONException: Value 0 of type java.lang.Integer cannot be converted to JSONObject
09-01 12:18:14.102  25321-25357/com.ems.employ W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)
09-01 12:18:14.102  25321-25357/com.ems.employ W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:160)
09-01 12:18:14.102  25321-25357/com.ems.employ W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:173)
09-01 12:18:14.102  25321-25357/com.ems.employ W/System.err﹕ at com.ems.employ.authenticatedemploy$SendMeterReadings.doInBackground(authenticatedemploy.java:114)
09-01 12:18:14.102  25321-25357/com.ems.employ W/System.err﹕ at com.ems.employ.authenticatedemploy$SendMeterReadings.doInBackground(authenticatedemploy.java:78)

1 个答案:

答案 0 :(得分:4)

您的JSON响应看起来不对,它有&#34; 0&#34;在开始时:0{"result":"4","name":"0"}我认为这是因为您的PHP代码中已取消注释echoecho $employname;

在Android应用程序代码中解析您的JSON之前,我建议您尝试使用常规浏览器获取它并确保JSON有效,您可以使用json lint进行此操作。