有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在安卓中下载JSON数据

我正在开发一个安卓应用程序,首先我向Web服务发送请求,并以0或1格式获取响应状态,如果响应为1,则加载完整的JSON文件。 我的问题是我想制作一个离线应用程序,我想从一个活动中下载JSON数据,并在不同的活动中读取这些数据,listview显示每个下载的JSON文件的标题。单击listview项后,将显示JSON数据。一些JSON数据项包含图像的URL,我也想下载它们并在另一个活动中显示它们。 我还想加密下载的JSON数据。请帮帮我

作为参考,我附上了JSON文件格式

{"test_time":7200,"time_taken":"0","time_left":"7200","score":null,"easy_score":null,"medium_score":null,"hard_score":null,"status":"n","sections":[{"section_id":"196498","section_name":"Reasoning Aptitude","section_no":1,"total_questions":"40","total_minutes":"24","questions":[{"question_id":"61562","question":{"1":{"text":"In a certain code GRANT is written as UOBSH and PRIDE is written as FEJSQ. How is SOLD written in that code?","image":"","imgHeight":"","imgWidth":""}},"correct_ans":{"1":{"text":"EMPT","image":"","imgHeight":"","imgWidth":""}},"rightOption":[],"rightOptionID":"246408","rightOptionNo":"2","anwer_explaination":{"1":{"text":"","image":"http://abc.com/testengine/images/questions/bankpower/image1.Jpeg","imgHeight":304,"imgWidth":212},"2":{"text":" ","image":"","imgHeight":"","imgWidth":""}},"question_time_taken":"10","marked":"0","skipped":"0","answer_id":"1395795","option_choose":"246407","question_status":1,"options":[{"OptionId":"246406","OptionDesc":{"1":{"text":"EPMT","image":"","imgHeight":"","imgWidth":""}}},{"OptionId":"246407","OptionDesc":{"1":{"text":"TPME","image":"","imgHeight":"","imgWidth":""}}},{"OptionId":"246408","OptionDesc":{"1":{"text":"EMPT","image":"","imgHeight":"","imgWidth":""}}},{"OptionId":"246409","OptionDesc":{"1":{"text":"CKNR","image":"","imgHeight":"","imgWidth":""}}},{"OptionId":"246410","OptionDesc":{"1":{"text":"ETPM","image":"","imgHeight":"","imgWidth":""}}}]},{"question_id":"61563","question":{"1":{"text":"Four of the following five are alike in a certain way and so form a group. Which is the one that does not belong to that group?","image":"","imgHeight":"","imgWidth":""}},"correct_ans":{"1":{"text":"27","image":"","imgHeight":"","imgWidth":""}},"rightOption":[],"rightOptionID":"246414","rightOptionNo":"3","anwer_explaination":{"1":{"text":"Mouse is odd rest are use for storage.","image":"","imgHeight":"","imgWidth":""}},"question_time_taken":"0","marked":"0","skipped":"1","answer_id":"","option_choose":"","question_status":3,"options":[{"OptionId":"246411","OptionDesc":{"1":{"text":"19","image":"","imgHeight":"","imgWidth":""}}},{"OptionId":"246412","OptionDesc":{"1":{"text":"17","image":"","imgHeight":"","imgWidth":""}}},{"OptionId":"246413","OptionDesc":{"1":{"text":"13","image":"","imgHeight":"","imgWidth":""}}},{"OptionId":"246414","OptionDesc":{"1":{"text":"27","image":"","imgHeight":"","imgWidth":""}}},{"OptionId":"246415","OptionDesc":{"1":{"text":"37","image":"","imgHeight":"","imgWidth":""}}}]}


共 (3) 个答案

  1. # 1 楼答案

    使用该链接中详述的解析器解析所有数据

    http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 然后使用下面的方法将所有数据写入一个文件,这样您的数据就会被下载并保存为文件

    public void appendData(String text)
    {       
        File myFile = new File("sdcard/myfile.file");
        if (!myFile.exists())
        {
          try
          {
              myFile.createNewFile();
          } 
          catch (IOException e)
          {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      }
      try
      {
          //BufferedWriter for performance, true to set append to file flag
          BufferedWriter buf = new BufferedWriter(new FileWriter(myFile, true)); 
          buf.append(text);
          buf.newLine();
          buf.close();
      }
      catch (IOException e)
      {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
    }
    
  2. # 2 楼答案

    您需要这样做:

       private class PrepareMapTask extends AsyncTask<String, Integer, Boolean>
        {
            // Initialize with invalid value
            private int mPrepareResult = -1;
            private String mJsonString = null;
    
            protected Boolean doInBackground(String... urls)
            {
                mJsonString = downloadFileFromInternet(urls[0]);
                if(mJsonString == null /*|| mJsonString.isEmpty()*/)
                    return false;
    
                JSONObject jObject = null;
                try {
                    jObject = new JSONObject(mJsonString);
                    JSONArray jsonImageArray = jObject.getJSONArray("imageTarget");
                    JSONArray jsonUrlArray = jObject.getJSONArray("videoUrls");
                    JSONArray jsonVideoOrUrlArray = jObject.getJSONArray("videoOrUrl");
                    if (jsonImageArray == null || jsonUrlArray == null)
                        return false;
                    for (int i = 0; i<jsonImageArray.length(); i++){ 
                        mapTargetUrl.put(jsonImageArray.get(i).toString(), jsonUrlArray.get(i).toString());
                        mVideoOrUrl.add(jsonVideoOrUrlArray.get(i).toString());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    return false;
                }
    
                return true;
            }
    
            protected void onPostExecute(Boolean result)
            {
            }
    
            private String downloadFileFromInternet(String url)
            {
                if(url == null /*|| url.isEmpty() == true*/)
                    new IllegalArgumentException("url is empty/null");
                StringBuilder sb = new StringBuilder();
                InputStream inStream = null;
                try
                {
                    url = urlEncode(url);
                    URL link = new URL(url);
                    inStream = link.openStream();
                    int i;
                    int total = 0;
                    byte[] buffer = new byte[8 * 1024];
                    while((i=inStream.read(buffer)) != -1)
                    {
                        if(total >= (1024 * 1024))
                        {
                            return "";
                        }
                        total += i;
                        sb.append(new String(buffer,0,i));
                    }
                }catch(Exception e )
                {
                    e.printStackTrace();
                    return null;
                }catch(OutOfMemoryError e)
                {
                    e.printStackTrace();
                    return null;
                }
                return sb.toString();
            }
    
            private String urlEncode(String url)
            {
                if(url == null /*|| url.isEmpty() == true*/)
                    return null;
                url = url.replace("[","");
                url = url.replace("]","");
                url = url.replaceAll(" ","%20");
                return url;
            }
    
        }
    

    根据json获取数据结构并修改代码

  3. # 3 楼答案

    try {
    
                      DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPostRequest = new HttpPost(URL);
    
    
            // Set HTTP parameters
            /*StringEntity se;
            se = new StringEntity(jsonObjSend.toString());*/
            jsonObjSend.length();
    
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(jsonObjSend.length());
            nameValuePairs.add(new BasicNameValuePair("data", jsonObjSend.toString()));
           // Log.i("jsonObjSend.toString()","jsonObjSend.toString()"+jsonObjSend.toString());
    
            Log.i("HTTPPOST","URL: "+URL);
            Log.i("HTTPPOST","Request: "+jsonObjSend.toString());
            UrlEncodedFormEntity en=new UrlEncodedFormEntity(nameValuePairs);
            en.getContent();
            httpPostRequest.getParams().setParameter("http.socket.timeout", new Integer(600000));
            httpPostRequest.setEntity(en);
            long t = System.currentTimeMillis();
            HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
            Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
            Log.i(TAG, httpPostRequest.getRequestLine().getProtocolVersion().toString());
            responses = convertEntityToString(response.getEntity(), "UTF-8");
            Log.i("HTTPPOST","Responce: "+responses);
            Log.i("HTTPPOST","******************");
            //Log.i("Encoding",response.getEntity().getContentEncoding().getName());
    
    
    
                    if (response.equalsIgnoreCase("")) {
                        webresponse = 1;
                    } else {
                        webresponse = 0;
                    }
                } catch (IOException e) {
                    h.post(new Runnable() {
    
                        @Override
                        public void run() {
                            pd.dismiss();
                            AlertNullWebserviceResponce();
    
                        }
                    });
    
                    e.printStackTrace();
                }