JSONException 故障排除:在字符 0 Android 处输入结束
Posted
技术标签:
【中文标题】JSONException 故障排除:在字符 0 Android 处输入结束【英文标题】:Troubleshooting JSONException: End of input at character 0 Android 【发布时间】:2017-08-17 23:01:19 【问题描述】:我遇到错误 JSONException 的问题。我的 doInBackground() 将 movieId 的参数(即 1(已记录))传递给 php 文件,然后 PHP 文件将执行查询并返回 json。在浏览器中运行适用于 JSON 响应。
import android.app.ProgressDialog;
import android.net.ParseException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* A simple @link Fragment subclass.
*/
public class FirstFragment extends Fragment
ImageView imageView;
TextView name, id;
public FirstFragment()
// Required empty public constructor
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_first, container, false);
imageView = (ImageView) rootView.findViewById(R.id.movie_image);
name = (TextView) rootView.findViewById(R.id.movie_name);
id = (TextView) rootView.findViewById(R.id.movie_id);
Bundle mBundle = new Bundle();
mBundle = getArguments();
name.setText(mBundle.getString("textMovieName"));
id.setText(mBundle.getString("textMovieId"));
Glide.with(getContext()).load(mBundle.getString("ivMovie"))
.placeholder(R.drawable.placeholder)
.error(R.drawable.ic_menu_camera)
.into(imageView);
new AsyncDate().execute(mBundle.getString("textMovieId"));
return rootView;
private class AsyncDate extends AsyncTask<String, String, String>
ProgressDialog pdLoading = new ProgressDialog(getActivity());
HttpURLConnection conn;
URL url = null;
@Override
protected void onPreExecute()
super.onPreExecute();
@Override
protected String doInBackground(String... params)
try
url = new URL("http://100.74.245.14/finalproject/date_time.php");
catch (MalformedURLException e)
e.printStackTrace();
return "exception";
//Log.d("params", params[0]);
try
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("movieId", params[0]);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
catch (IOException e1)
e1.printStackTrace();
return "exception";
try
int response_code = conn.getResponseCode();
if (response_code == HttpURLConnection.HTTP_OK)
//Log.d("response","ok");
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
result.append(line);
Log.d("return", result.toString());
return (result.toString());
else
return "unsuccessful";
catch (IOException e2)
e2.printStackTrace();
return "exception";
finally
conn.disconnect();
@Override
protected void onPostExecute(String result)
List<listMovie> data = new ArrayList<>();
try
JSONObject jsonObj = new JSONObject(result);
JSONArray jArray = jsonObj.getJSONArray("test");
//Log.d("json", result);
for (int i = 0; i < jArray.length(); i++)
//Log.d("json", "test");
JSONObject json_data = jArray.getJSONObject(i);
listMovie movieData = new listMovie();
movieData.movieDate = json_data.getString("date");
movieData.movieTime = json_data.getString("time");
data.add(movieData);
catch (JSONException e)
e.printStackTrace();
PHP 文件
<?php
include 'config.inc.php';
if(isset($_POST['movieId']))
$movieId= $_POST['movieId'];
$sql = 'SELECT * FROM movie_time WHERE movie_id = :movie_id';
$stmt = $conn -> prepare($sql);
$stmt -> bindParam(':movie_id', $movieId, PDO::PARAM_STR);
$result = $stmt -> execute();
if($result)
while($row = $stmt->fetchAll(PDO::FETCH_ASSOC))
$flag['test'] = $row;
header('Content-type: application/json');
echo json_encode($flag);
?>
我得到的错误
W/System.err: org.json.JSONException: End of input at character 0 of
W/System.err: at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
W/System.err: at org.json.JSONTokener.nextValue(JSONTokener.java:97)
W/System.err: at org.json.JSONObject.<init>(JSONObject.java:155)
W/System.err: at org.json.JSONObject.<init>(JSONObject.java:172)
W/System.err: at com.example..fyp.FirstFragment$AsyncDate$override.onPostExecute(FirstFragment.java:153)
W/System.err: at com.example.fyp.FirstFragment$AsyncDate$override.access$dispatch(FirstFragment.java)
W/System.err: at com.example.fyp.FirstFragment$AsyncDate.onPostExecute(FirstFragment.java:0)
W/System.err: at com.example.fyp.FirstFragment$AsyncDate.onPostExecute(FirstFragment.java:75)
W/System.err: at android.os.AsyncTask.finish(AsyncTask.java:632)
W/System.err: at android.os.AsyncTask.access$600(AsyncTask.java:177)
W/System.err: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err: at android.os.Looper.loop(Looper.java:136)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5017)
W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
W/System.err: at dalvik.system.NativeStart.main(Native Method)
在这一行
JSONObject jsonObj = new JSONObject(result);
【问题讨论】:
【参考方案1】:很难确定这一点,但我敢打赌,您在打开/关闭 php 标记之前/之后会有一些空格或换行符。
检查 php 打开标记 (
【讨论】:
【参考方案2】:您将 movie_id 参数附加为 URL 查询参数(在您的 Java 代码中),但在 PHP $_POST
数组中查找:这是行不通的。
要么更改您的 PHP 以同时查看 $_POST
和 $_GET
,要么更改您的 Java 以实际执行正确的 POST 请求。
另外,附带说明一下,您可能只想在 doInBackground
内调用 new JSONObject()
:在后台线程上进行 JSON 解析并在执行中处理解析的对象更有效。
编辑:您可能还想设置内容类型标头(尝试conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
【讨论】:
以上是关于JSONException 故障排除:在字符 0 Android 处输入结束的主要内容,如果未能解决你的问题,请参考以下文章