gpt4 book ai didi

java - 组织.json.JSONException : End of input at character 0

转载 作者:行者123 更新时间:2023-11-30 08:21:33 26 4
gpt4 key购买 nike

我已经坚持了一段时间。根本无法弄清楚出了什么问题。一双新鲜的眼睛会很有帮助。我不断收到 org.json.JSONException: End of input at character 0 of 并且无法弄清楚。

我的 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;

}
}

Activity

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: End of input at character 0 of 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): at 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): at 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): Error converting result java.lang.NullPointerException: lock == null 08-05 09:53:03.371: E/JSON Parser(3072): Error parsing data org.json.JSONException: End of input at character 0 of

最佳答案

org.json.JSONException: End of input at character 0

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

同时我会给你一些建议:

PHP

  • 不确定 INSERT 是否成功,但我注意到您没有使用 $db 变量。
  • 您愿意使用已弃用的 mysql 扩展进行 sql 注入(inject)
  • 你应该在你的 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);
?>

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;

}

异步任务

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 execute,在那里记录 json 对象,如果您在日志中得到任何内容,就可以开始解析。使用 boolean 值会更容易。

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

关于java - 组织.json.JSONException : End of input at character 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25140857/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com