java org.json.JSONException: 字符 0 处的输入结束
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25140857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
org.json.JSONException: End of input at character 0
提问by upasna21
I have been stuck on this for a while. Simply cannot figure out whats wrong. A pair of fresh eyes would be very helpful. I keep on getting the org.json.JSONException: End of input at character 0 of and cannot figure it out.
我已经坚持了一段时间。根本无法弄清楚出了什么问题。一双新鲜的眼睛会很有帮助。我不断收到 org.json.JSONException: End of input at character 0 of 并且无法弄清楚。
My JSONParser
我的 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();
}
}
My Php
我的 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);
}
?>
And my error:
我的错误:
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
08-05 09:53:03.321: W/System.err(3072): org.json.JSONException: 08-05 09:53:03.321 字符 0 处的输入结束:W/System.err(3072): at 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):在 org. json.JSONArray.(JSONArray.java:108) 08-05 09:53:03.331: W/System.err(3072): 在 com.lta.fine.JSONParser.makeHttpRequest(JSONParser.java:60) 08-05 09 :53:03.341:W/System.err(3072):在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: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):在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)08-05 09:53:03.361:W/System.err(3072):在java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 08-05 09:53:03.361: W/System.err(3072): 在 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): Error parsing数据 org.json.JSONException:字符 0 处的输入结束
回答by meda
org.json.JSONException: End of input at character 0
org.json.JSONException: 字符 0 处的输入结束
Usually means you are not getting any JSON. you will need to debug your app to find out why.
通常意味着你没有得到任何 JSON。您需要调试您的应用程序以找出原因。
In the mean time I will give you some pointers:
同时,我会给你一些提示:
PHP
PHP
- Not sure if the INSERT is successful but I noticed you are not using
$db
variable. - You are open to sql injection using deprecated mysql extension
- you should use boolean in your json
- echo the json at the end.
- 不确定 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);
?>
Java:
爪哇:
- I see that your method returns a
JSONObject
that limits you already from parsing arrays. Instead return the json as string then parse it. - You are parsing the data inside of the method, this makes it more difficult to use.
- I see little to no reason to use
GET
you might as well split that function.
- 我看到您的方法返回一个
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
}
In doInbackground
perform the request and pass the result to post execute, log the json object there, if you get anything in the log you can start parsing. using boolean value it will be easier.
在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();
}
回答by 0xb304
Your is
(member var?) isn't set for the POST case. Could its value be left over from some previous request?
您的is
(成员变量?)没有为 POST 案例设置。它的值是否可以从之前的某个请求中遗留下来?
In general, good idea to use local vars wherever possible.
一般来说,尽可能使用本地变量是个好主意。