JSON 文字列応答を取得するために Web サービスを呼び出していますが、元の文字列にはないバックスラッシュが含まれています。以下は、 {"name":"Name","id":1}である JSON 文字列オブジェクトを要求するための私のコードです。
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());
}
}
Rsponse 文字列は次のとおりです: "{\"name\":\"Name\",\"id\":1}" そして、それを JSONObject に解析しようとすると、次のような例外がスローされます: org.json.JSONException 値 "{ "name":"Name","id":1}"型は json オブジェクトに変換できません。