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

Android 解析嵌入在url中的json对象数组,android,json,parsing,asynchronous,Android,Json,Parsing,Asynchronous,然而,我不断得到这些例外。我也在下面发布了我的日志。我是android新手,所以我需要帮助。url由json对象数组组成 [ { "codeField":"COMPSCI 101", "semesterField":"Summer School; Semester 1; Semester 2", "titleField":"Principles of Programming" }, { "codeField":"COMPSCI 1

然而,我不断得到这些例外。我也在下面发布了我的日志。我是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;
    }

}

正如alread告诉您的,您的doInBackground必须返回一个JSonObject not null:change

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


谢谢你对人们的帮助。我已经解决了这个问题,并将解析后的内容转换为列表视图。这是我的工作代码:

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));
        }
        }
package com.example.compsci_734t;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.UnsupportedEncodingException;
导入java.net.URL;
导入java.util.ArrayList;
导入java.util.zip.gzip输入流;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.StatusLine;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.Activity;
导入android.app.ListActivity;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.widget.ArrayAdapter;
导入android.widget.ListView;
公共阶层人士扩大活动{
ArrayList items=新建ArrayList();
静态InputStream为空;
//私有静态字符串url=“”;
//私有静态字符串url=“http:…”;
私有静态字符串url=“http…”;
//URL requestUrl=新URL(URL);
JSONArray-people=null;
私有静态最终字符串TAG_COURSES=“COURSES”;
静态JSONObject jObj=null;
静态字符串json=“”;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.people);
新建MyTasks().execute();
}
私有类MyTasks扩展了AsyncTask{
@凌驾
受保护的JSONObject doInBackground(URL…URL){
//返回loadJSON(url);
试一试{
//defaultHttpClient
DefaultHttpClient httpClient=新的DefaultHttpClient();
//HttpPost HttpPost=新的HttpPost(url);
HttpGet HttpGet=新的HttpGet(url);
HttpResponse HttpResponse=httpClient.execute(httpGet);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
/*BufferedReader reader=新的BufferedReader(新的InputStreamReader(
为“UTF-8”)、8)*/
InputStream InputStream=is;
GZIPInputStream输入=新的GZIPInputStream(inputStream);
InputStreamReader reader=新的InputStreamReader(输入);
BufferedReader in=新的BufferedReader(读卡器);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=in.readLine())!=null){
某人附加(行);
//系统输出打印项次(行);
}
is.close();
json=sb.toString();
}捕获(例外e){
Log.e(“缓冲区错误”,“错误转换结果”+e.toString());
}
//尝试将字符串解析为JSON对象
试一试{
JSONArray people=新的JSONArray(json);
//JSONArray people=新的JSONArray(json);
for(int i=0;i
可能是重复的。在最后一页中,试图更正它的空间不足。发布您的JSONParser代码并发布logcat错误。应该使用codeField而不是CourseField。我发布了我的json解析器代码。我做了这些更改,现在仍然为您的所有帮助人员提供了一个例外。我已经解决了它并转换了解析的代码填充到列表视图中。以下是我的工作代码:
        @Override
        protected JSONObject doInBackground(URL... urls) {
            loadJSON(url);
            return null;
        }
        @Override
        protected JSONObject doInBackground(URL... urls) {
            return loadJSON(url);;
        }
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));
        }
        }