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

时间:2018-01-15 22:09:25

标签: android json parsing

我正在尝试反向服务器json数据。

我的代码: MainActivity

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}

3 个答案:

答案 0 :(得分:0)

通过传递输入流

来调用此方法
    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);

答案 1 :(得分:0)

错误的原因是因为您期望以这种形式出现的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解析的更多信息,请参阅此tutorial。另请查看我的answer如何使用Gson创建的库来轻松映射JSON。

答案 2 :(得分:0)

我的代码是真的。问题是截然不同的地方。

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

谢谢大家。