我正在调用 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;
}
在执行后我只是尝试将此响应字符串解析为 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 value "{ "name":"Name","id":1}"类型无法转换为 json 对象。