在Android上从URL检索JSON

前端之家收集整理的这篇文章主要介绍了在Android上从URL检索JSON前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的手机APP在文本模式下完美下载内容.下面是一个代码来做到这一点.我调用Communicator类和exectueHttpGet:

URL_Data = new Communicator().executeHttpGet(“Some URL”);

  1. public class Communicator {
  2. public String executeHttpGet(String URL) throws Exception
  3. {
  4. BufferedReader in = null;
  5. try
  6. {
  7. HttpClient client = new DefaultHttpClient();
  8. client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,"android");
  9. HttpGet request = new HttpGet();
  10. request.setHeader("Content-Type","text/plain; charset=utf-8");
  11. request.setURI(new URI(URL));
  12. HttpResponse response = client.execute(request);
  13. in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
  14.  
  15. StringBuffer sb = new StringBuffer("");
  16. String line = "";
  17.  
  18. String NL = System.getProperty("line.separator");
  19. while ((line = in.readLine()) != null)
  20. {
  21. sb.append(line + NL);
  22. }
  23. in.close();
  24. String page = sb.toString();
  25. //System.out.println(page);
  26. return page;
  27. }
  28. finally
  29. {
  30. if (in != null)
  31. {
  32. try
  33. {
  34. in.close();
  35. }
  36. catch (IOException e)
  37. {
  38. Log.d("BBB",e.toString());
  39. }
  40. }
  41. }
  42. }
  43. }

我记得的是这个(URL的源代码):

  1. [{"id_country":"3","country":"AAA"},{"id_country":"8","country":"BBB"},{"id_country":"66","country":"CCC"},{"id_country":"14","country":"DDD"},{"id_country":"16","country":"EEE"},{"id_country":"19","country":"FFF"},{"id_country":"24","country":"GGG"},{"id_country":"33","country":"HHH"},{"id_country":"39","country":"III"},{"id_country":"44","country":"JJJ"},{"id_country":"45","country":"KKK"},{"id_country":"51","country":"LLL"},{"id_country":"54","country":"MMM"},{"id_country":"55","country":"NNN"},{"id_country":"57","country":"OOO"},{"id_country":"58","country":"PPP"},{"id_country":"63","country":"RRR"},{"id_country":"65","country":"SSS"}]

这个响应是一个字符串.在服务器上,它作为JSON对象输出(使用PHP),现在在我的Android PHP中,我希望将此字符串转换为JSON.这可能吗?

解决方法

你收到的是InputStream中的一系列字符,你追加到StringBuffer并在最后转换为String – 所以String的结果是ok

猜你在找的Android相关文章