如何解决JSON错误:解析数据错误[输入结束于字符0]


How to solve JSON error: Error parsing data [End of input at character 0 of ]

我是这一级别的编程新手,想学习JSON并了解其工作原理。我遇到了这个特定用户关于堆栈溢出的问题,想知道如何以及在哪里使用给他的答案。

用户代码为:

    private ProgressDialog pDialog;
    JSONParser jsonParser = new JSONParser();
    EditText inputDriver;
    EditText inputLicence;
    EditText inputOfficer;
    EditText inputSpeed;
    EditText FineAppl;
    EditText inputCategory;
    TextView registerFine;
    // url to create new fine
    private static String url_create_fine = "http://192.168.1.1/android_api/create.php";
    // JSON Node names/
    private static final String TAG_SUCCESS = "success";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        speed = (EditText) findViewById(R.id.editText3);    
        Fine = (TextView)findViewById(R.id.editText4);  
        btnSelectDate=(Button)findViewById(R.id.buttonSelectDate);
        btnSelectTime=(Button)findViewById(R.id.buttonSelectTime);
        inputDriver = (EditText) findViewById(R.id.editText1);
        inputLicence = (EditText) findViewById(R.id.editText2);
        inputOfficer = (EditText) findViewById(R.id.editText5);
        inputSpeed = (EditText) findViewById(R.id.editText3);
        FineAppl = (EditText) findViewById(R.id.editText4);
        inputCategory = (EditText) findViewById(R.id.editText6);
        registerFine = (TextView) findViewById(R.id.fineregistered);

        // Create button
       Button btnRegisterfine = (Button) findViewById(R.id.savefine);
       class CreateNewFine extends AsyncTask<String, String, String> {

                            @Override
                            protected void onPreExecute() {
                                super.onPreExecute();
                                pDialog = new ProgressDialog(FineCalc.this);
                                pDialog.setMessage("Registering Fine..");
                                pDialog.setIndeterminate(false);
                                pDialog.setCancelable(true);
                                pDialog.show();
                            }

                            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 for success tag
                               try {
                                    if(json != null && !(json).isNull(TAG_SUCCESS)){
                                    //registerFine.setText("");
                                    String success = json.getString(TAG_SUCCESS);
                                    if(success != null && success.length() > 0){
                                        // successfully created product
                                       Intent i = new Intent(getApplicationContext(), UserLogin.class);
                                        startActivity(i);
                                        //registerFine.setText("Successful");

                                        // closing this screen
                                        finish();
                                    } 
                    else {
                                    }   // failed to create product
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                return null;
                            }

                            protected void onPostExecute(String file_url) {
                                // dismiss the dialog once done
                                pDialog.dismiss();
                            }
                        }  

JSONParser是:

      public class JSONParser {
    static InputStream is = null;
static JSONObject jObj = null;
    static String json = "";
   // constructor
    public 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 httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }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();
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        //BufferedReader reader = new BufferedReader(new InputStreamReader(
               // is, HTTP.UTF_8), 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());
        Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
    }
    // return JSON String
    return jObj;
}

}    

         <?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  finereg(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);
 }
  ?>

在log cat上显示的唯一错误是:

     08-04 05:47:48.799: E/JSON Parser(1506): Error parsing data [End of input at character 0 of ]

有人给出的答案是实现以下内容。那么在上面的代码中如何以及在哪里实现以下内容

    HttpResponse response = client.execute(httpPost);
    String responseBody = EntityUtils.toString(response.getEntity());
     pass the string into json array and get the response value
        JSONArray jsArray = new JSONArray(responseBody);
        JSONObject js = jsArray.getJSONObject(0);
        String returnvalmsg = js.getString("message");
        String returnvalsucc = js.getString("success");

构造函数不返回数据库连接,一旦有了对象,就可以访问返回数据库连接的方法:

require_once 'include/DB_Connect.php';
$db = new DB_Connect();
$conn = $db->connect();
$result = mysql_query("INSERT INTO fineregister(driver,licencenum,officer,speed,fine,category)
                       VALUES('$driver','$licencenum','$officer','$speed','$fine','$category')"
           , $conn);