微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Android上从URL检索JSON

我的手机APP在文本模式下完美下载内容.下面是一个代码来做到这一点.我调用Communicator类和exectueHttpGet:

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

public class Communicator {
public String executeHttpGet(String URL) throws Exception 
{
    BufferedReader in = null;
    try 
    {
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,"android");
        HttpGet request = new HttpGet();
        request.setHeader("Content-Type","text/plain; charset=utf-8");
        request.setURI(new URI(URL));
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";

        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) 
        {
            sb.append(line + NL);
        }
        in.close();
        String page = sb.toString();
        //System.out.println(page);
        return page;
    } 
    finally 
    {
        if (in != null) 
        {
            try 
            {
                in.close();
            } 
            catch (IOException e)    
            {
                Log.d("BBB",e.toString());
            }
        }
    }
}
}

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

[{"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

原文地址:https://www.jb51.cc/android/313691.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐