嗨我在2.3版中遇到了Android JSON Parser的问题,4.0版本都没问题。
我看其他主题他们正在谈论编码(服务器)或其他服务器端,但我试图在我的所有JSON字段中放置“test”,问题仍然存在。
这是我的代码:
URL url = new URL(c.getString(R.string.url_ws) + url_ws);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
OutputStreamWriter request = new OutputStreamWriter(connection.getOutputStream());
request.write("&test=test");
request.flush();
request.close();
String line;
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
String json = sb.toString().trim();
try {
JSONObject obj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
Log.d(Tools.TAG+"/debug JSONException", e.toString());
return null;
}
这是我的例外
debug JSONException(4184): org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject
我在“Value”和“of”之间看到了双倍空格,所以我猜问题是一个空字符串,但我不明白。
感谢。
修改
这是我JSON中的编码错误,
char a = json.substring(0, 1).charAt(0);
int ascii = (int)a;
Tools.myLog(">"+ascii+"<");
我找到65279 char
Why is  appearing in my HTML?
编码没有BOM的UTF-8。
答案 0 :(得分:1)
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
而不是尝试
while ((line = reader.readLine()) != null){
sb.append(line);
json = sb.toString().substring(0, sb.toString().length()-1);
}
按照此方法获取json对象:
public JSONObject getJSONObjFromUrl(String url, List<NameValuePair> params) {
System.out.println("url:: "+url );
System.out.println("params:: "+ params +" " +params.get(0) );
// Making HTTP request
try {
// defaultHttpClient
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);
}
is.close();
json = sb.toString().substring(0, sb.toString().length()-1);
// Log.e("JSON:: ", json);
} 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;
}