解析url中嵌入的json对象数组

时间:2013-05-13 10:32:45

标签: android json parsing asynchronous

但是我一直得到这些例外。我还在下面发布了我的logcat。我是android的新手,所以我需要帮助。 url由一组json对象组成。

[
   {
      "codeField":"COMPSCI 101",
      "semesterField":"Summer School; Semester 1; Semester 2",
      "titleField":"Principles of Programming"
   },
   {
      "codeField":"COMPSCI 105",
      "semesterField":"Summer School; Semester 1; Semester 2",
      "titleField":"Principles of Computer Science"
   },
   ......
]

代码:

package com.example.compsci_734t;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class UoaCompsciActivity extends Activity {

    private static String url = "http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/courses";
    //URL requestUrl = new URL(url);
    JSONArray courses = new JSONArray();
    private static final String TAG_COURSES = "Courses";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_uoa_compsci);
        new MyTask().execute();
    }


    private class MyTask extends AsyncTask<URL, Void, JSONObject> {

        @Override
        protected JSONObject doInBackground(URL... urls) {
            loadJSON(url);
            return null;
        }

        protected void onPostExecute(JSONObject json) {

            try {
                courses = json.getJSONArray(TAG_COURSES);

                // looping through all courses
                for (int i = 0; i < courses.length(); i++) {
                    JSONObject c = courses.getJSONObject(i);

                    // Storing each json item in variable
                    String course_id = c.getString("courseField:");
                    String course_name = c.getString("titleField:");
                    String course_semester = c.getString("semesterField:");



                    Log.v("--", "Course: \n" + " " + course_id + " " + course_name
                            + " " + course_semester);
                }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    }


    public JSONObject loadJSON(String url) {
        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
         JSONObject json = jParser.getJSONFromUrl(url);

        return json;
    }

}

这是我更新的代码:现在在logcat中只获得一个异常: 05-13 23:02:04.309:E / JSON Parser(1213):解析数据时出错org.json.JSONException:Value

package com.example.compsci_734t;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class UoaCompsciActivity extends Activity {

    private static String url = "http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/courses";
    //URL requestUrl = new URL(url);
    JSONArray courses = null;
    //private static final String TAG_COURSES = "Courses";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_uoa_compsci);
        new MyTask().execute();
    }


    private class MyTask extends AsyncTask<URL, Void, JSONObject> {

        @Override
        protected JSONObject doInBackground(URL... urls) {
            return loadJSON(url);

        }

        protected void onPostExecute(JSONObject json) {
            String var = "Courses";
            //JSONArray courses = new JSONArray(var);
            try {
                JSONArray courses = new JSONArray(var);

                // looping through all courses
                for (int i = 0; i < courses.length(); i++) {
                    JSONObject c = courses.getJSONObject(i);

                    // Storing each json item in variable
                    String course_id = c.getString("codeField:");
                    String course_name = c.getString("titleField:");
                    String course_semester = c.getString("semesterField:");



                    Log.v("--", "Course: \n" + " " + course_id + " " + course_name
                            + " " + course_semester);
                }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    }


    public JSONObject loadJSON(String url) {
        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
         JSONObject json = jParser.getJSONFromUrl(url);

        return json;
    }

}

这是我的jsonparser代码

package com.example.compsci_734t;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

2 个答案:

答案 0 :(得分:0)

正如已经告诉你的那样,你的doInBackground必须返回一个JSonObject而不是null:更改

        @Override
        protected JSONObject doInBackground(URL... urls) {
            loadJSON(url);
            return null;
        }

        @Override
        protected JSONObject doInBackground(URL... urls) {
            return loadJSON(url);;
        }

答案 1 :(得分:0)

感谢您的帮助。我已经解决了它并将解析后的内容转换为列表视图。这是我的工作代码:

package com.example.compsci_734t;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;





import android.app.Activity;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;



public class People extends Activity{

        ArrayList<String> items = new ArrayList<String>();
        static InputStream is = null;
        //private static String url = "";
        //private static String url = "http:...";
        private static String url = "http....";
        //URL requestUrl = new URL(url);
        JSONArray people = null;
        private static final String TAG_COURSES = "Courses";
        static JSONObject jObj = null;
        static String json = "";

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.people);
            new MyTasks().execute();
        }


        private class MyTasks extends AsyncTask<URL, Void, JSONObject> {

            @Override
            protected JSONObject doInBackground(URL... urls) {
               // return loadJSON(url);
                try {
                    // defaultHttpClient
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    //HttpPost httpPost = new HttpPost(url);
                    HttpGet httpGet = new HttpGet(url);
                    HttpResponse httpResponse = httpClient.execute(httpGet);

                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
              try {
                /*BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "UTF-8"), 8);*/
                InputStream inputStream = is;
                GZIPInputStream input = new GZIPInputStream(inputStream);
                InputStreamReader reader = new InputStreamReader(input);
                BufferedReader in = new BufferedReader(reader);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = in.readLine()) != null) {
                    sb.append(line);
                   //System.out.println(line);
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }

            // try parse the string to a JSON object

            try {

                JSONArray people = new JSONArray(json);
                //JSONArray people = new JSONArray(json);

                for (int i = 0; i < people.length(); i++) {
                    //System.out.println(courses.getJSONObject(i).toString());
                    JSONObject p = people.getJSONObject(i);

                    // Storing each json item in variable
                    String person_id = p.getString("someString1");


                    items.add(person_id);

                    /*Log.v("--", "People: \n" + "\n UPI: " + person_id);*/
                }


                //jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            } 

            // return JSON String
            return jObj;
            }

            protected void onPostExecute(JSONObject json) {
                ListView myListView = (ListView)findViewById(R.id.peopleList);
                myListView.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, items));
        }
        }