Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Android上从URL检索JSON_Android_Json - Fatal编程技术网

在Android上从URL检索JSON

在Android上从URL检索JSON,android,json,Android,Json,我的手机应用程序以文本模式完美下载内容。下面是这样做的代码。我调用Communicator类和exectueHttpGet: URL\u Data=newcommunicator().executeHttpGet(“一些URL”) 我收到的是(URL的源代码): 此响应是一个字符串。在服务器上,它作为JSON对象输出(使用PHP),现在在我的Android PHP中,我想将这个字符串转换为JSON。这可能吗?您是否尝试过将内容类型设置为application/json?使用org.json.JS

我的手机应用程序以文本模式完美下载内容。下面是这样做的代码。我调用Communicator类和exectueHttpGet:

URL\u Data=newcommunicator().executeHttpGet(“一些URL”)

我收到的是(URL的源代码):


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

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

使用org.json.JSONObject,如中所示

JSONObject json = new JSONObject(oage);
需要注意的是,当响应只是“true”或“false”时,可能需要创建一个util函数来检查这些情况,否则只需加载JSONObject

好的,在本例中,您将使用JSONArray

JSONArray jsonArray = new JSONArray(page); 
for (int i = 0; i < jsonArray.length(); ++i) {
  JSONObject element = jsonArray.getJSONObject(i);
  ..... 
}
JSONArray JSONArray=新的JSONArray(第页);
对于(int i=0;i
您收到的是来自
输入流的一系列字符,您将这些字符附加到
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
}
String page=newcommunicator().executeHttpGet(“某些URL”);
JSONArray JSONArray=新JSONArray(第页);
for(int i=0;i
编辑:

为了进一步说明我之前链接到您的问题,请使用此示例。将它放在一个返回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);
/End编辑

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();
}
尝试阅读我在这个问题上发布的解决方案:

嗯,

斯图

试试看 ///

JSONArray JSONArray=新JSONArray(responseString)

for(JSONObject JSONObject:jsonArray) { ……
}


////..

假设我们有一个名为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();
}
公共列表getData(字符串URL)引发InterruptedException、ExecutionException{ //这必须是异步任务,因为来自远程web服务器的数据流应该在后台线程而不是主线程中运行。否则,在连接和获取数据时,应用程序将挂起。 AsyncTask getTask=新建AsyncTask(){ @凌驾 受保护列表doInBackground(字符串…参数){ List postList=new ArrayList(); 字符串响应=”; 试一试{ //从url开始读取流数据 java.net.URL URL=新的java.net.URL(参数[0]); HttpURLConnection urlConnection=(HttpURLConnection) openConnection(); BufferedReader=new BufferedReader(new InputStreamReader(urlConnection.getInputStream()); 字符串行=”; 而((line=reader.readLine())!=null){ 响应+=行+“\n”; } //从url端读取流数据 //从Response数据开始解析json数据 JSONArray JSONArray=新JSONArray(响应);
对于(inti=0;i
try{URL_Data=newcommunicator().executeHttpGet(“某些URL”);JSONObject jObject=newjsonobject(URL_Data);}catch(异常e){Log.d(“AAAA”,“Napaka”+e.toString())}
尝试后,调试器说:
04-07 08:44:54.719:DEBUG/AAAA(370):Napaka org.json.JSONException:Value[{“id\u country”:“3”,“country”:org.json.JSONArray类型的“AAA”}、{“id_country”:“8”、“country”:“BBB”}、…]无法转换为JSONObject
我的意思是进一步处理从上面发布的方法返回的字符串“page”。是的,绝对是……这正是我所做的……new Communicator().executeHttpGet(“某个url”)在上面的代码中,返回值页。它是一个字符串(请参见问题-页面顶部)现在我不知道如何使它可用…好的,对不起-我误解了你。我明白了…它现在工作了问题是在emulator中…它因为未知的原因被压碎了…谢谢!这将帮助客户端检测到这是Json数据,但不会自动将内容转换为Json。不…问题是我只收到一个写为的字符串尝试如下:
JSONArray-JSONArray=new-JSONArray(URL_数据);for(JSONObject-JSONObject:JSONArray){}
但得到错误:只能迭代一个数组或java.lang.IterableHi的一个实例,这些只是从服务器请求的小数据。基本上,大部分存储在手机数据库的第一顿午餐上。动态部分(每天都在更改)是根据请求加载的。但我想要的是转换收到的字符串(如页面顶部有问题的字符串)要在Android平台中使用…请参阅我编辑的答案。它将适用于您的解决方案,用于处理少量和大量数据。此服务器上的响应为字符串或空白,这是我检查数据是否存在的方式。字符串始终表示由PHP创建的JSON(上面的示例)。唯一的问题是现在如何处理它…好的,为此您需要JSONArray并使用for循环进行迭代:
JSONArray JSONArray=new JSONArray(URL_数据);
for(int i=0;i
`JSONObject element=JSONArray.getJSONObject(i);`code>..
我不知道如何正确设置注释的格式,但基本上是加载数组,检查其长度,然后在JSONArrayI上使用getJSONObject。它现在可以工作了。问题出在emulator中…它因为未知原因而崩溃了
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();
}