解析JSON对象时遇‘End of input at character 0’错误求助
问题分析与解决方案
我来帮你拆解下遇到的问题,逐个解决:
1. 服务器返回的JSON格式不合法
你贴出的服务器响应内容是多个JSONObject直接用逗号拼接,但没有用[]包裹,这不是合法的JSON数组格式。正确的合法格式应该是:
[{"id":"16165","sensorid":"cc3200_8A7F30","pm1":"0.22","pm25":"0.23","pm10":"0.41","timestamp":"2018-01-30 12:28:56.000"},{"id":"16166","sensorid":"cc3200_E271A6","pm1":"0","pm25":"0.02","pm10":"0.46","timestamp":"2018-01-30 12:30:15.000"},{"id":"16167","sensorid":"cc3200_8A7F30","pm1":"0.09","pm25":"0.09","pm10":"0.58","timestamp":"2018-01-30 12:30:56.000"},{"id":"16168","sensorid":"cc3200_E271A6","pm1":"0.07","pm25":"0.07","pm10":"0.26","timestamp":"2018-01-30 12:32:15.000"}]
如果没法要求服务器修改返回格式,你可以在客户端手动给响应内容前后加上[],把它转换成合法的JSONArray。
2. 网络请求代码的错误导致空响应
你的sendGet方法里有两个明显的问题,这也是你出现End of input at character 0的直接原因:
- 你先获取了
InputStream inputStr = con.getInputStream();但没有使用,之后又再次调用con.getInputStream()创建BufferedReader。一个HttpURLConnection的输入流只能被读取一次,第二次获取的流是空的; con.setRequestProperty("api-key");和con.setRequestProperty("api-code");写法错误,该方法需要传入键值对,比如con.setRequestProperty("api-key", "你的key值");,否则请求可能不被服务器正确处理,返回空内容。
修正后的sendGet方法示例:
private String sendGet() throws Exception { String url = "myUrl"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", USER_AGENT); // 修正请求头写法,传入键和对应的值 con.setRequestProperty("api-key", "你的API_KEY"); con.setRequestProperty("api-code", "你的API_CODE"); int responseCode = con.getResponseCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); if (responseCode == 200) { // 只获取一次输入流 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 返回响应内容 return response.toString(); } else { // 处理非200响应,读取错误流排查问题 BufferedReader errorIn = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); String inputLine; StringBuffer errorResponse = new StringBuffer(); while ((inputLine = errorIn.readLine()) != null) { errorResponse.append(inputLine); } errorIn.close(); System.err.println("Error response: " + errorResponse.toString()); return null; } }
3. JSON解析逻辑错误
你的解析代码试图从JSONObject里获取名为particles的数组,但服务器返回的内容(修正格式后)本身就是一个JSONArray,根本没有particles这个键。你需要直接把响应字符串转换成JSONArray,而不是先转成JSONObject。
修正后的解析代码:
@Override protected Void doInBackground(Void... voids) { HttpHandler sh = new HttpHandler(); String jsonString = sh.makeServiceCall(url); Log.e(TAG, "Response from url: " + jsonString); System.out.println("jsonstring: " + jsonString); if (jsonString != null && !jsonString.isEmpty()) { // 手动修正服务器返回的非法JSON格式:前后加[] if (!jsonString.startsWith("[") && !jsonString.endsWith("]")) { jsonString = "[" + jsonString + "]"; } try { // 直接解析成JSONArray JSONArray particles = new JSONArray(jsonString); for (int i = 0; i < particles.length(); i++) { JSONObject c = particles.getJSONObject(i); String id = c.getString("id"); String sensorid = c.getString("sensorid"); String pm1 = c.getString("pm1"); String pm25 = c.getString("pm25"); String pm10 = c.getString("pm10"); String timestamp = c.getString("timestamp"); HashMap<String, String> particle = new HashMap<>(); particle.put("id", id); particle.put("sensorid", sensorid); particle.put("pm1", pm1); particle.put("pm25", pm25); particle.put("pm10", pm10); particle.put("timestamp", timestamp); // 记得把particle添加到你的数据列表中,比如mParticleList.add(particle); } } catch (final JSONException e) { Log.e(TAG, "Json Parsing error: " + e.getMessage()); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Json Parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } }); } } else { Log.e(TAG, "Couldn't get json from server."); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG) .show(); } }); } return null; }
总结解决步骤
- 修复网络请求代码中的输入流重复获取问题,以及请求头的正确写法;
- 修正服务器返回的非法JSON格式(服务器不能改则客户端手动加[]);
- 调整解析逻辑,直接解析JSONArray而不是寻找不存在的
particles键。
内容的提问来源于stack exchange,提问作者Kkona
相关产品推荐
相关产品推荐

