我正在调用一个Web服务以获取JSON字符串响应,但它包含了不在原始字符串中的反斜杠。下面是我请求JSON字符串对象的代码:{"name":"Name","id":1}。
protected String doInBackground(String... uri)
{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
在post execute中,我只是尝试将这个响应字符串解析为JSONObject。代码如下:
protected void onPostExecute(String result) {
super.onPostExecute(result);
TextView t1=(TextView)findViewById(R.id.textView1);
TextView t2=(TextView)findViewById(R.id.textView2);
//String s = result.replaceAll("\\", ""); //I have tried to escape backslashes also using this line.
String name="failure";
int id;
try
{
t1.setText(result);
JSONObject reader = new JSONObject(result.toString()); //Exception on this line.
//name = reader.getString("name").toString();
//id = reader.getInt("id");
t2.setText(name);
}
catch (Exception e)
{
t2.setText(e.toString());
}
}
响应字符串为:"{\"name\":\"Name\",\"id\":1}",当我尝试将其解析为JSONObject时,会抛出异常,提示org.json.JSONException值"{"name":"Name","id":1}"类型无法转换为json对象。