Retrieving JSON from URL on Android

前端 未结 6 1786
无人共我
无人共我 2020-12-03 12:56

My phone APP downloads content perfectly in a text mode. Below is a code to do that. I call Communicator class and exectueHttpGet:

URL_Data = new Communicator(

相关标签:
6条回答
  • 2020-12-03 13:14

    use org.json.JSONObject as in

    JSONObject json = new JSONObject(oage);
    

    thing to watch out for is when the response is simply "true" or "false." probably want to create a util function that checks for those cases, otherwise just load up the JSONObject.

    ok in this case you would use a JSONArray

    JSONArray jsonArray = new JSONArray(page); 
    for (int i = 0; i < jsonArray.length(); ++i) {
      JSONObject element = jsonArray.getJSONObject(i);
      ..... 
    }
    
    0 讨论(0)
  • 2020-12-03 13:17

    just try like

    ///...

    JSONArray jsonArray = new JSONArray(responseString);

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

    ////..

    0 讨论(0)
  • 2020-12-03 13:23

    Assume that we have a POJO class called Post

    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();
    }
    
    0 讨论(0)
  • 2020-12-03 13:27

    Have you tried setting the content type to application/json?

    0 讨论(0)
  • 2020-12-03 13:28

    What you receive is a series of characters from the InputStream that you append to a StringBuffer and convert to String at the end - so the result of String is ok :)

    What you want is to post-process this String via org.json.* classes like

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

    and then work on jsonObject. As the data you receive is an array, you can actually say

    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
    }
    
    0 讨论(0)
  • 2020-12-03 13:34

    EDIT:

    To further the question I linked you to earlier, use this example. put it in a function that returns a JSONArray (so then you can loop through the array and use array.getString). This works for most amounts of data. It will send the correct compression headers to the web server and detect a gzip compressed result also. Try it:

        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 Edit

    Try reading the solution I posted on this SO question:

    Create list in android app

    Hth,

    Stu

    0 讨论(0)
提交回复
热议问题