Android JSON 异常(字符 0 处的输入结束)



我正在尝试检索服务器json数据。

我的代码:主活动

String url = "http://........com/...../...."
String[] params = new String[]{url};
JSONParser jsonParser = new JSONParser();
try {
String response = jsonParser.execute(url).get();
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObje = (JSONObject) jsonArray.get(0);
}

JSONParser.JAVA

HttpURLConnection connection = null;
BufferedReader reader = null;
String responseText="";
        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            //GIVE ERROR THIS LINE!
            InputStream stream = connection.getInputStream();
            //ERROR LINE!
            reader = new BufferedReader(new InputStreamReader(stream));

错误:org.json.JSONException:字符 0 处的输入结束

Json 文件:

{"PersonelID":2,"PersonelAdıSoyadı":"New Driver","PersonelTelefon":"","PersonelMail":"driver@mail.com","PersonelPassword":null,"PersonelTipi":1,"AracID":0,"SirketID":20,"SuccessCode":1}

只需通过传递输入流来调用此方法

    private String readInputStream(InputStream inputStream) throws IOException {
    Log.d(TAG, "readInputStream()");
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader bufferedReader = null;
    try {
        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            bufferedReader = new BufferedReader(inputStreamReader);
            String line = bufferedReader.readLine();
            while (line != null) {
                stringBuilder.append(line);
                line = bufferedReader.readLine();
            }
            return stringBuilder.toString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bufferedReader != null) {
            bufferedReader.close();
        }
    }
    return "RESULT_EMPTY";
}

,然后JSONObject jsonObject = new JSONObject(result);

错误

的原因是因为您期望以这种形式获得JSONArray

["item1","item2,"item3"]

虽然JSONObject是这种形式{"key": "value"}所以在你的例子中,你得到的是JSONObject,而不是JSONArray.因此,请将您的代码更改为

String response = jsonParser.execute(url).get();
JSONObject jsonObject = new JSONObject(resonse);
String PersonelMail= jsonObject.getString("PersonelMail");
 //...... the same for  the other values

有关 JSON 解析的更多信息,请参阅本教程。 另请查看我的答案,了解如何使用谷歌创建的库 Gson 轻松映射 JSON。

我的代码是正确的。问题在非常不同的地方。

我正在向Android清单添加互联网权限,问题已解决。

谢谢大家。

最新更新