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

时间:2014-08-05 14:07:56

标签: java json android-asynctask

我被困在这一段时间了。根本无法弄清楚什么是错的。一双新鲜的眼睛会非常有帮助。我继续得到org.json.JSONException:字符0处的输入结束,并且无法弄明白。

我的JSONParser

 public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse response = httpClient.execute(httpPost);
            String responseBody = EntityUtils.toString(response.getEntity());
            //HttpEntity httpEntity = httpResponse.getEntity();
            //is = httpEntity.getContent();
           JSONArray jsArray = new JSONArray(responseBody);
           JSONObject js = jsArray.getJSONObject(0);
           String returnvalmsg = js.getString("message");
           String returnvalsucc = js.getString("success");

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }          

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
   // } catch (JSONException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;


        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();

    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

  }
}

活动

btnRegisterfine.setOnClickListener(new View.OnClickListener() {

                             @Override
                            public void onClick(View view) {
                                // creating new product in background thread
                                new CreateNewFine().execute();
                            }


                      });
    }

                      /**
                         * Background Async Task to Register Fine
                         * */
                        class CreateNewFine extends AsyncTask<String, String, String> {

                            /**
                             * Before starting background thread Show Progress Dialog
                             * */
                            @Override
                            protected void onPreExecute() {
                                super.onPreExecute();
                                pDialog = new ProgressDialog(Finecalc.this);
                                pDialog.setMessage("Registering Fine..");
                                pDialog.setIndeterminate(false);
                                pDialog.setCancelable(true);
                                pDialog.show();
                            }

                            /**
                             * Registering Fine
                             * */
                            protected String doInBackground(String... args) {
                                String driver = inputDriver.getText().toString();
                                String licencenum = inputLicence.getText().toString();
                                String officer = inputOfficer.getText().toString();
                                String speed = inputSpeed.getText().toString();
                                String fine= FineAppl.getText().toString();
                                String category = inputCategory.getText().toString();


                                // Building Parameters
                                List<NameValuePair> params = new ArrayList<NameValuePair>();
                                params.add(new BasicNameValuePair("driver", driver));
                                params.add(new BasicNameValuePair("licencenum", licencenum));
                                params.add(new BasicNameValuePair("officer", officer));
                                params.add(new BasicNameValuePair("speed", speed));
                                params.add(new BasicNameValuePair("fine", fine));
                                params.add(new BasicNameValuePair("category", category));

                                // getting JSON Object
                                // Note that create product url accepts POST method
                                JSONObject json = jsonParser.makeHttpRequest(url_create_fine,
                                        "POST", params);

                                // check log cat fro response
                                Log.d("Create Response", json.toString());

                                // check for success tag
                                try {
                                    int success = json.getInt(TAG_SUCCESS);

                                    if (success == 1) {
                                        // successfully Registered Fine
                                        //Intent i = new Intent(getApplicationContext(), Finecalc.class);
                                        //startActivity(i);
                                        registerFine.setText("DONE");
                                        // closing this screen
                                        finish();
                                    } else {
                                        // failed to Register Fine
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                                return null;
                            }

                            /**
                             * After completing background task Dismiss the progress dialog
                             * **/
                            protected void onPostExecute(String file_url) {
                                // dismiss the dialog once done
                                pDialog.dismiss();
                            }

                        }

我的Php

<?php

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['driver'], $_POST['licencenum'], $_POST['officer'], $_POST['speed'] , $_POST['fine'],$_POST['category'])){

    $driver = $_POST['driver'];
 $licencenum = $_POST['licencenum'];
 $officer = $_POST['officer'];
    $speed = $_POST['speed'];
    $fine = $_POST['fine'];
    $category = $_POST['category'];


    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    // mysql inserting a new row
$result = mysql_query("INSERT INTO fineregister(driver,licencenum,officer,speed,fine,category) VALUES   ('$driver','$licencenum','$officer','$speed','$fine',      '$category')");

    // check if row inserted or not
 if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Speed Ticket Successfully Registered.";

    // echoing JSON response
    echo json_encode($response);
    } else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    // echoing JSON response
    echo json_encode($response);
 }
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}
?>

我的错误:

  

08-05 09:53:03.321:W / System.err(3072):org.json.JSONException:字符0的输入结束   08-05 09:53:03.321:W / System.err(3072):at org.json.JSONTokener.syntaxError(JSONTokener.java:450)   08-05 09:53:03.321:W / System.err(3072):at org.json.JSONTokener.nextValue(JSONTokener.java:97)   08-05 09:53:03.331:W / System.err(3072):at org.json.JSONArray。(JSONArray.java:92)   08-05 09:53:03.331:W / System.err(3072):at org.json.JSONArray。(JSONArray.java:108)   08-05 09:53:03.331:W / System.err(3072):at com.lta.fine.JSONParser.makeHttpRequest(JSONParser.java:60)   08-05 09:53:03.341:W / System.err(3072):at com.lta.fine.MainActivity $ CreateNewFine.doInBackground(MainActivity.java:191)   08-05 09:53:03.341:W / System.err(3072):at com.lta.fine.MainActivity $ CreateNewFine.doInBackground(MainActivity.java:1)   08-05 09:53:03.351:W / System.err(3072):在android.os.AsyncTask $ 2.call(AsyncTask.java:288)   08-05 09:53:03.351:W / System.err(3072):at java.util.concurrent.FutureTask.run(FutureTask.java:237)   08-05 09:53:03.361:W / System.err(3072):在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:231)   08-05 09:53:03.361:W / System.err(3072):at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)   08-05 09:53:03.361:W / System.err(3072):at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:587)   08-05 09:53:03.361:W / System.err(3072):at java.lang.Thread.run(Thread.java:841)   08-05 09:53:03.361:E / Buffer Error(3072):转换结果时出错java.lang.NullPointerException:lock == null   08-05 09:53:03.371:E / JSON Parser(3072):解析数据时出错org.json.JSONException:

字符0的输入结束

2 个答案:

答案 0 :(得分:3)

  

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

通常意味着您没有获得任何JSON。您需要调试应用程序以找出原因。

与此同时,我会给你一些指示:

<强> PHP

  • 不确定INSERT是否成功但我注意到您没有使用$db变量。
  • 您可以使用弃用的mysql扩展名
  • 打开sql注入
  • 你应该在你的json中使用boolean
  • 最后回复了json。

<?php

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['driver'], $_POST['licencenum'], $_POST['officer'], $_POST['speed'] , $_POST['fine'],$_POST['category'])){

    $driver = $_POST['driver'];
    $licencenum = $_POST['licencenum'];
    $officer = $_POST['officer'];
    $speed = $_POST['speed'];
    $fine = $_POST['fine'];
    $category = $_POST['category'];


    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    // mysql inserting a new row
    $result = mysql_query("INSERT INTO fineregister(driver,licencenum,officer,speed,fine,category) VALUES   ('$driver','$licencenum','$officer','$speed','$fine','$category')");

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = true;
        $response["message"] = "Speed Ticket Successfully Registered.";
        // echoing JSON response
    } else {
        // failed to insert row
        $response["success"] = false;
        $response["message"] = "Oops! An error occurred.";
    }
} else {
    // required field is missing
    $response["success"] = false;
    $response["message"] = "Required field(s) is missing";
}
    // echoing JSON response
    echo json_encode($response);
?>

<强>爪哇:

  • 我看到您的方法返回JSONObject,这已经限制了您 解析数组。而是将json作为字符串返回,然后解析它。
  • 您正在解析方法内部的数据,这使得它更多 难以使用。
  • 我认为很少甚至没有理由使用GET你可能会将其分开 功能

public String makeHttpRequest(String url, List<NameValuePair> params) 
{
    InputStream is = null;
    String json = "";

    // Making HTTP request
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();


    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();

        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }


    // return JSON String
    return json;

}

<强>的AsyncTask

protected String doInBackground(String... args) {
    String driver = inputDriver.getText().toString();
    String licencenum = inputLicence.getText().toString();
    String officer = inputOfficer.getText().toString();
    String speed = inputSpeed.getText().toString();
    String fine= FineAppl.getText().toString();
    String category = inputCategory.getText().toString();


    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("driver", driver));
    params.add(new BasicNameValuePair("licencenum", licencenum));
    params.add(new BasicNameValuePair("officer", officer));
    params.add(new BasicNameValuePair("speed", speed));
    params.add(new BasicNameValuePair("fine", fine));
    params.add(new BasicNameValuePair("category", category));

    // getting JSON String
    // Note that create product url accepts POST method
    String json = jsonParser.makeHttpRequest(url_create_fine, params);

    return json;
}



protected void onPostExecute(String json) {
    // dismiss the dialog once done
    pDialog.dismiss();
    Log.d("mylog", "json = " + json);
    //parse here
}

doInbackground执行请求并将结果传递给post执行,在那里记录json对象,如果你在日志中得到任何东西就可以开始解析。使用布尔值会更容易。

try {
    JSONObject jsonData = new JSONObject(json);
    Boolean success = jsonData.getBoolean("success");
    String message = jsonData.getString("message");

    if (success) {
    //success
    } else {
    // failed to Register Fine
    }
} catch (JSONException e) {
    e.printStackTrace();
}

答案 1 :(得分:0)

您的is(成员var?)未设置为POST案例。它的价值可以从以前的一些请求中遗留下来吗?

一般情况下,尽可能使用本地变量。