我已经编写了Android类,它将调用RESTful Web服务。如果请求成功,则 响应将是JSON对象。我写的android类是这样的:如何将JSON响应转换为字符串并在屏幕中显示?
公共类的Android扩展活动{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView txt = (TextView) findViewById(R.id.textView1);
txt.setText(getInputStreamFromUrl("http://localhost:8080/kyaw"));
}
public static String getInputStreamFromUrl(String url) {
InputStream content = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
content = response.getEntity().getContent();
} catch (Exception e) {
Log.e("[GET REQUEST]", "Network exception");
}
String result=convert(content);
return result;
}
private static String convert(InputStream in)
{
BufferedReader reader=new BufferedReader(new InputStreamReader(in));
StringBuilder sb=new StringBuilder();
String line=null;
try{
while((line=reader.readLine())!=null){
sb.append(line+"\n");
}
}catch(Exception e)
{
e.printStackTrace();
}finally{
try{
in.close();
}catch(IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
}
我有一个问题后,我run.I会得到异常怎么我返回的响应string.But是JSON。我应该如何将JSON转换为字符串或其他方式,然后如何在Android屏幕上显示结果?
感谢
什么异常? FC?来自服务器的JSON响应是一个字符串。 – Selvin 2011-05-19 07:47:36
嗨selvin,当我运行类andriod虚拟设备提醒我有异常然后关闭,但不显示什么异常。我调试它,我发现在HttpResponse响应= httpclient.execute(新HttpGet(URL))异常; 。我不知道为什么,我是新来的 – sudo 2011-05-19 07:57:09
首先启用Logcat http://stackoverflow.com/questions/3280051/how-to-enable-logcat-in-eclipse。第二提供日志从logcat窗口 – Selvin 2011-05-19 07:59:24