[英]org.json.JSONException: End of input at character 0
我已經堅持了一段時間。 根本無法找出問題所在。 一雙新鮮的眼睛將非常有幫助。 我繼續獲取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:輸入結束於08-05 09:53:03.321的字符0:W / System.err(3072):在org.json.JSONTokener.syntaxError(JSONTokener.java:450)08-05 09:53:03.321:W / System.err(3072):位於org.json.JSONTokener.nextValue(JSONTokener.java:97)08-05 09:53:03.331:W / System.err(3072):在org.json.JSONArray。(JSONArray.java:92)08-05 09:53:03.331:W / System.err(3072):在組織。 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) :位於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):位於java.util.concurrent.FutureTask.run(FutureTask.java:237)08-05 09:53:0 3.361:W / System.err(3072):在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:231)08-05 09:53:03.361:W / System.err(3072):在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的輸入結束
org.json.JSONException:字符0的輸入結束
通常意味着您沒有得到任何JSON。 您將需要調試應用程序以找出原因。
同時,我會給您一些提示:
PHP
$db
變量。 <?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);
?>
Java的:
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
執行請求並將結果傳遞給后期執行,在其中記錄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();
}
您的is
(成員var?)未設置為POST情況。 它的值可以保留在先前的請求中嗎?
通常,最好在可能的地方使用局部變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.