org.json.JSONException:字符0的输入结束

时间:2016-06-30 06:02:44

标签: java php android json android-volley

Volley库中的JSONObjectRequest存在一些问题,无法接收JSON数据。我想我在接收Java代码中的JSON对象时出错了。以下是我的JSON输出,作为服务器上托管的php文件的响应:

{"workers":[
           {"id":"1","name":"Raja","phonenumber":"66589952","occupation":"Plumber","location":"Salunke Vihar","rating":"4","Review":"Hard Worker","price":"80"},
           {"id":"2","name":"Aman","phonenumber":"789456","occupation":"Plumber","location":"Wakad","rating":"4","Review":"Good","price":"80"}
          ],
"success":1}

以下是来自Java文件的clode,我正在使用Volley库使用JSON请求:

JsonObjectRequest jsonRequest = new JsonObjectRequest (Request.Method.POST, url,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        // I should receive the success value 1 here
                        int success = response.getInt("success");
                        //and should receive the workers array here
                        Log.d("response",response.getJSONArray("workers").toString());
                        Log.d("success",""+success);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
                    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

                    recyclerView.setHasFixedSize(true);
                    layoutManager = new LinearLayoutManager(getApplicationContext());
                    recyclerView.setLayoutManager(layoutManager);
                    //Finally initializing our adapter
                    adapter = new WorkerAdapter(listWorkers);
                    recyclerView.setAdapter(adapter);
                   //adapter is working fine
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                   Log.d("error",error.toString());
                    Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            params.put("tag", "get_list");
            params.put("service", service);
            return params;
        }

运行上面的代码,它转到错误监听器,并将输出作为org.json.JSONException:输入结束于字符0的。 但是,如果我使用StringRequest代替JsonObjectRequest并以字符串形式接收JSON响应,那么我能够以字符串形式接收输出,但我无法进一步使用它。所以,请告诉我收到JSONdata时出错的地方,并建议我必须做的代码更改。

编辑 - 我正在添加返回JSON对象的php文件。如果此处有错误,请告知我们:

<?php
error_reporting(0);
include("config.php");

if($_SERVER['REQUEST_METHOD']=='POST'){    
$tag = $_POST['tag'];
// array for JSON response
$response = array();

if ($tag == 'get_list') {
// Request type is check Login
$service = $_POST['service'];

//echo json_encode($service);   

// get all items from myorder table
$result = mysql_query("SELECT * FROM Workers WHERE Occupation = '$service'") or die(mysql_error());

if (mysql_num_rows($result) > 0) {

    $response["workers"] = array();

    while ($row = mysql_fetch_array($result)) {
            // temp user array
            $item = array();
            $item["id"] = $row["wID"];
            $item["pic"] = $row["Pic"];
            $item["name"] = $row["Name"];
            $item["phonenumber"] = $row["Phone Number"];
            $item["occupation"] = $row["Occupation"];
            $item["location"] = $row["Location"];
            $item["rating"] = $row["Rating"];
            $item["Review"] = $row["Review"];
            $item["price"] = $row["Price"];


            // push ordered items into response array
            array_push($response["workers"], $item);
           }
      // success
     $response["success"] = 1;
}
else {
    // order is empty
      $response["success"] = 0;
      $response["message"] = "No Items Found";
}
}   
echo json_encode($response);    
}
?>

3 个答案:

答案 0 :(得分:0)

你能检查服务器是否返回JSONObject而不是字符串?在Volley中,如果响应类型不同,则会返回错误。

答案 1 :(得分:0)

您可以使用Gson将json字符串转换为对象

var data = Request.Content.ReadAsByteArrayAsync().Result;

这对我有用。

答案 2 :(得分:0)

当我运行api终点时,我得到了以下结果,而不是你所说的那个结果。因此,请停止提供无关数据。

"Plumber"{"workers":[{"id":"1","pic":"ttp:\/\/vorkal.com\/images\/vorkal_cover.PNG","name":"Raja","phonenumber":"66589952","occupation":"Plumber","location":"Salunke Vihar","rating":"4","Review":"Hard Worker. Very Professional.","price":"80"},{"id":"2","pic":"http:\/\/vorkal.com\/images\/vorkal_cover.PNG","name":"Aman","phonenumber":"789456","occupation":"Plumber","location":"Wakad","rating":"4","Review":"Good","price":"80"}],"success":1}

Plumber根本不是标记,因此抛出错误,因为它不是有效的json字符串。 您的服务器端脚本存在错误。我请求您发送完整的脚本而不进行修改。

如果您未收到JSONObject,则表示以下内容格式错误json。因此,您可以在服务器端尝试以下代码

 function utf8ize($d) {
if (is_array($d)) {
    foreach ($d as $k => $v) {
        $d[$k] = $this->utf8ize($v);
    }
} else if (is_string ($d)) {
    return utf8_encode($d);
}
return $d;
}

其中$d是字符串/响应。将其用作echo json_encode($this->utf8ize($detail));

在客户端代码中尝试以下内容

Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(result1));
reader.setLenient(true);

您可以在click here

中找到此问题的解决方案