在我的应用程序中我从服务器获得J SON格式的响应。在解析时,它在响应中显示未终止的错误。因此无法解析它。
我的json编码
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpConnectionParams.setSoTimeout(client.getParams(), 10000);
HttpResponse response;
try {
HttpPost post = new HttpPost(getString(R.string.base_url)+ "login?json=");
Time dtNow = new Time();
dtNow.setToNow();
String last_login_ts = dtNow.format("%Y-%m-%d %H:%M:%S");
// Log.v("Login_ts",""+last_login_ts);
json.put("pmailtxt", "" + et_username.getText().toString());
json.put("loginpasstxt", "" + et_password.getText().toString());
json.put("merchant_code", "" + getString(R.string.merchant_code));
json.put("last_login_ts", "" + last_login_ts);
// Log.v("Login", ""+json);
// Toast.makeText(getApplicationContext(), ""+json, 700).show();
post.setHeader("json", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
post.setEntity(se);
response = client.execute(post);
// Checking response
if (response != null) {
// get a data
InputStream in = response.getEntity().getContent();
String a = json_res_class.convertStreamToString(in);
Log.v("Response", ""+a);//here am getting response
此处我的回复错误
06-07 16:05:55.132: W/System.err(930): org.json.JSONException: Unterminated array at character 5 of [ {"loginSuccess":0,"message":"Wrong username or password"}]
我如何纠正这个问题,任何人都知道请帮助我解决这个问题。
答案 0 :(得分:1)
异常消息很明显...... JSON的最后一个字符缺失,因此您的数组未关闭。因为它没有关闭,所以无法解析。
此外,在解析的情况下,您应该捕获异常。
答案 1 :(得分:1)
查看以下代码
try {
HttpResponse response = httpclient.execute(httppost);
int responsecode = response.getStatusLine().getStatusCode();
if (responsecode == 200) {
InputStream in = response.getEntity().getContent();
resultstring = Util.convertinputStreamToString(in);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
检查你的convertinputStreamToString函数一次。
public static String convertinputStreamToString(InputStream ists)
throws IOException {
if (ists != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader r1 = new BufferedReader(new InputStreamReader(
ists, "UTF-8"));
while ((line = r1.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
ists.close();
}
return sb.toString();
} else {
return "";
}
}