【问题标题】:Retrieving JSON from URL on Android在 Android 上从 URL 检索 JSON
【发布时间】:2011-04-07 08:07:36
【问题描述】:

我的手机APP以文本模式完美下载内容。下面是执行此操作的代码。我调用 Communicator 类并执行 HttpGet:

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());
            }
        }
    }
}
}

我收到的是这个(网址的源代码):

[{"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。这可能吗?

【问题讨论】:

    标签: android json


    【解决方案1】:

    您收到的是来自InputStream 的一系列字符,您附加到StringBuffer 并在最后转换为String - 所以String 的结果是可以的:)

    你想要的是通过org.json.* 类对这个字符串进行后处理

    String page = new Communicator().executeHttpGet("Some URL");
    JSONObject jsonObject = new JSONObject(page);
    

    然后处理jsonObject。由于你收到的数据是一个数组,你其实可以说

    String page = new Communicator().executeHttpGet("Some URL");
    JSONArray jsonArray = new JSONArray(page);
    for (int i = 0 ; i < jsonArray.length(); i++ ) {
      JSONObject entry = jsonArray.get(i);
      // now get the data from each entry
    }
    

    【讨论】:

    • try {URL_Data = new Communicator().executeHttpGet("some url"); JSONObject jObject = new JSONObject(URL_Data); } catch (Exception e) { Log.d("AAAA", "Napaka " + e.toString()); } 尝试此操作后,调试器会说:04-07 08:44:54.719: DEBUG/AAAA(370): Napaka org.json.JSONException: Value [{"id_country":"3","country":"AAA"},{"id_country":"8","country":"BBB"},...] of type org.json.JSONArray cannot be converted to JSONObject
    • 我的意思是进一步处理您从上面发布的方法返回的字符串'page'。
    • 是的,绝对是……这正是我所做的……上面代码中的 new Communicator().executeHttpGet("some url") 返回值页面。它是一个字符串(见问题 - 页面顶部),现在我不知道如何使它可用......
    • 好的,对不起 - 我误会了你。
    • 我明白了..现在可以了,问题出在模拟器中...由于未知原因而崩溃...谢谢!
    【解决方案2】:

    编辑:

    要进一步了解我之前链接到您的问题,请使用此示例。把它放在一个返回 JSONArray 的函数中(这样你就可以遍历数组并使用 array.getString)。这适用于大多数数据量。它会将正确的压缩头发送到 Web 服务器并检测 gzip 压缩结果。试试看:

        URL url = new URL('insert your uri here');
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setRequestProperty("Accept-Encoding", "gzip");
        HttpURLConnection httpConn = (HttpURLConnection) urlConn;
        httpConn.setAllowUserInteraction(false);
        httpConn.connect();
        if (httpConn.getContentEncoding() != null) {
            String contentEncoding = httpConn.getContentEncoding().toString();
            if (contentEncoding.contains("gzip")) {
            in = new GZIPInputStream(httpConn.getInputStream());
            }
            // else it is encoded and we do not want to use it...
        } else {
            in = httpConn.getInputStream();
        }
        BufferedInputStream bis = new BufferedInputStream(in);
        ByteArrayBuffer baf = new ByteArrayBuffer(1000);
        int read = 0;
        int bufSize = 1024;
        byte[] buffer = new byte[bufSize];
        while (true) {
            read = bis.read(buffer);
            if (read == -1) {
            break;
            }
            baf.append(buffer, 0, read);
        }
        queryResult = new String(baf.toByteArray());
        return new JSONArray(queryResult);
    

    /结束编辑

    尝试阅读我在这个 SO 问题上发布的解决方案:

    Create list in android app

    第,

    学习

    【讨论】:

    • 嗨,这些只是来自服务器的少量请求数据。基本上大部分存储在手机数据库的第一次午餐时。动态部分(每天都在变化)根据要求加载。但我想要的是转换接收到的字符串(如页面顶部的问题)以在 Android 平台中使用...
    • 查看我编辑的答案。它适用于处理少量和大量数据的解决方案。
    【解决方案3】:

    使用 org.json.JSONObject

    JSONObject json = new JSONObject(oage);
    

    需要注意的是响应只是“真”或“假”。可能想要创建一个 util 函数来检查这些情况,否则只需加载 JSONObject。

    好的,在这种情况下你会使用 JSONArray

    JSONArray jsonArray = new JSONArray(page); 
    for (int i = 0; i < jsonArray.length(); ++i) {
      JSONObject element = jsonArray.getJSONObject(i);
      ..... 
    }
    

    【讨论】:

    • 此服务器上的响应是字符串或空白,这是我检查数据是否存在的方式。字符串始终代表 PHP 创建的 JSON(示例如上)。唯一的问题是现在如何处理......
    • 好吧,你需要 JSONArray 并使用 for 循环遍历:JSONArray jsonArray = new JSONArray(URL_Data); for (int i = 0; i &lt; jsonArray.length(); ++i) { ` JSONObject element = jsonArray.getJSONObject(i);` ..... }
    • 我不知道如何正确格式化评论,但基本上你加载数组,检查它的长度,然后在 JSONArray 上使用 getJSONObject
    • 我明白了..它现在可以工作了,问题出在模拟器中...它因未知原因而崩溃...谢谢!
    【解决方案4】:

    您是否尝试将内容类型设置为application/json

    【讨论】:

    • 这将帮助客户端检测到这是 Json 数据,但不会自动将这些东西变成 Json。
    • 好吧,不。关键是我只收到了上面写的字符串。
    【解决方案5】:

    假设我们有一个名为 Post

    的 POJO 类
    public List<Post> getData(String URL) throws InterruptedException, ExecutionException {
        //This has to be AsyncTask because data streaming from remote web server should be running in background thread instead of main thread. Or otherwise your application will hung while connecting and getting data.
        AsyncTask<String,String, List<Post>> getTask = new AsyncTask<String,String,List<Post>>(){
            @Override
            protected List<Post> doInBackground(String... params) {
                List<Post> postList  = new ArrayList<Post>();
                String response = "";
                try{
                    //Read stream data from url START
                    java.net.URL url = new java.net.URL(params[0]);
                    HttpURLConnection urlConnection = (HttpURLConnection)
                            url.openConnection();
                    BufferedReader reader = new  BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    String line = "";
                    while((line = reader.readLine()) != null){
                        response += line + "\n";
                    }
                    //Read stream data from url END
    
                    //Parsing json data from reponse data START
                    JSONArray jsonArray = new JSONArray(response);
                    for(int i=0;i<jsonArray.length();i++){
    
                        String message = jsonArray.getJSONObject(i).getString("message");
                        // Post class has a constructor which accept message value.
                        postList.add(new Post(message));
                    }
                    //Parsing json data from reponse data END
                } catch (Exception e){
                    e.printStackTrace();
                }
    
                return postList;
            }
    
            protected void onPostExecute(String result) {
            }
        };
        //This will return a list of posts
        return getTask.execute(URL).get();
    }
    

    【讨论】:

      【解决方案6】:

      试试就好

      ///...

      JSONArray jsonArray = new JSONArray(responseString);

      for(JSONObject jsonObject:jsonArray) { .........
      }

      ////..

      【讨论】:

      • 试过这样:JSONArray jsonArray = new JSONArray(URL_Data); for(JSONObject jsonObject:jsonArray) {} 但出现错误:只能遍历数组或 java.lang.Iterable 的实例
      猜你喜欢
      • 2015-07-12
      • 2016-02-10
      • 2016-06-04
      • 1970-01-01
      • 1970-01-01
      • 2015-02-06
      • 2014-11-27
      • 1970-01-01
      • 2023-04-09
      相关资源
      最近更新 更多