簡體   English   中英

無法在Android中的HTTP請求中獲取JSON

[英]Can't get JSON in HTTP Request in Android

我正在嘗試接收Android中拋出JSON的HTTP格式文件。 但是當我這樣做時,我猜該文件的格式不正確。 代碼如下:

@Override
        protected String doInBackground(String... params) {
            StringBuilder builder = new StringBuilder();
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();

                URI website = new URI(params[0]);

                HttpGet request = new HttpGet();
                request.setHeader("Content-type", "application/json");
                request.setURI(website);
                HttpResponse httpResponse = httpClient.execute(request);
                HttpEntity entity = httpResponse.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                    builder.append(line);
                }
            }
            catch(Exception e){
                Log.e("http", e.toString());
            }

            return builder.toString();
        }


@Override
        protected void onPostExecute(String result) {
            try {
                JSONObject jObject = new JSONObject(result);
                txt.setText((String) jObject.get("shortName"));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //txt.setText(result);
        }

JSON文件如下所示:

{"lectiveSemesters":[{"lectiveSemesterId":1,"shortName":"0910i","startYear":2009,"term":1,"termName":"Fall","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/1","root":"http://thoth.cc.e.ipl.pt/api/v1"}},{"lectiveSemesterId":2,"shortName":"0910v","startYear":2009,"term":2,"termName":"Spring","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/2","root":"http://thoth.cc.e.ipl.pt/api/v1"}},{"lectiveSemesterId":3,"shortName":"1011i","startYear":2010,"term":1,"termName":"Fall","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/3","root":"http://thoth.cc.e.ipl.pt/api/v1"}},
...
...
"_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters"}}

這只是文件的一部分。

難道我做錯了什么? 我包括標頭以便以JSON格式接收。

這個給你。 try{ JSONObject jObject = new JSONObject(result); JSONArray jarray = jObject.getJSONArray("lectiveSemesters"); for(int i = 0; jarray != null & i < jarray.length(); i++){ JSONObject jitem = (JSONObject) jarray.get(i); } } catch (Exception e){ }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM