我试图在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){ }

10-06 13:58