0

以下数据在一个网址中:我如何使用 JSon 解析它以阅读课程代码:COMPSCI 101,提供的学期:暑期学校,第 1 学期,第 2 学期课程名称:编程原理............ ...等等??

[{"codeField":"COMPSCI 101","semesterField":"暑期学校;第一学期;第二学期","titleField":"编程原理"},{"codeField":"COMPSCI 105","semesterField" :"暑期学校;第一学期;第二学期","titleField":"计算机科学原理"},{"codeField":"COMPSCI 111/111G","semesterField":"暑期学校;第一学期;第二学期" ,"titleField":"掌握网络空间:实用计算简介"}]

我尝试了这段代码,但它在运行时在模拟器上抛出了一个异常,说“不幸的是 JsonParsing 已停止工作”。请原谅我的天真错误,因为我是 android 新手:package com.example.jsonparsing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.view.Menu;
import android.widget.ArrayAdapter;

public class JsonActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json);
        setListAdapter(new ArrayAdapter(
                this,android.R.layout.simple_list_item_1,
                this.populate()));
    }

    private ArrayList<String> populate() {
        ArrayList<String> items = new ArrayList<String>();

        try {
            URL url = new URL
            ("http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/courses");
            HttpURLConnection urlConnection =
                (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
                        // gets the server json data
            BufferedReader bufferedReader =
                new BufferedReader(new InputStreamReader(
                        urlConnection.getInputStream()));

            String next;
            while ((next = bufferedReader.readLine()) != null){
                JSONArray ja = new JSONArray(next);

                for (int i = 0; i < ja.length(); i++) {
                    JSONObject jo = (JSONObject) ja.get(i);
                    items.add(jo.getString("text"));

                }
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return items;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_json, menu);
        return true;
    }

}

这也是我的日志:

05-11 12:25:34.151: I/Process(77): Sending signal. PID: 722 SIG: 3
05-11 12:25:34.161: I/dalvikvm(722): threadid=3: reacting to signal 3
05-11 12:25:34.231: I/dalvikvm(722): Wrote stack traces to '/data/anr/traces.txt'
05-11 12:25:34.281: D/AndroidRuntime(722): Shutting down VM
05-11 12:25:34.281: W/dalvikvm(722): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
05-11 12:25:34.291: E/AndroidRuntime(722): FATAL EXCEPTION: main
05-11 12:25:34.291: E/AndroidRuntime(722): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonparsing/com.example.jsonparsing.JsonActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.ActivityThread.access$600(ActivityThread.java:123)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.os.Looper.loop(Looper.java:137)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.ActivityThread.main(ActivityThread.java:4424)
05-11 12:25:34.291: E/AndroidRuntime(722):  at java.lang.reflect.Method.invokeNative(Native Method)
05-11 12:25:34.291: E/AndroidRuntime(722):  at java.lang.reflect.Method.invoke(Method.java:511)
05-11 12:25:34.291: E/AndroidRuntime(722):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-11 12:25:34.291: E/AndroidRuntime(722):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-11 12:25:34.291: E/AndroidRuntime(722):  at dalvik.system.NativeStart.main(Native Method)
05-11 12:25:34.291: E/AndroidRuntime(722): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.ListActivity.onContentChanged(ListActivity.java:243)
05-11 12:25:34.291: E/AndroidRuntime(722):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:254)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.Activity.setContentView(Activity.java:1835)
05-11 12:25:34.291: E/AndroidRuntime(722):  at com.example.jsonparsing.JsonActivity.onCreate(JsonActivity.java:26)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.Activity.performCreate(Activity.java:4465)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
05-11 12:25:34.291: E/AndroidRuntime(722):  ... 11 more
05-11 12:25:34.301: W/ActivityManager(77):   Force finishing activity com.example.jsonparsing/.JsonActivity
05-11 12:25:34.301: W/WindowManager(77): Failure taking screenshot for (180x300) to layer 21010
05-11 12:25:34.574: I/Process(77): Sending signal. PID: 722 SIG: 3
05-11 12:25:34.574: I/dalvikvm(722): threadid=3: reacting to signal 3
05-11 12:25:34.581: I/dalvikvm(722): Wrote stack traces to '/data/anr/traces.txt'
05-11 12:25:34.825: W/ActivityManager(77): Activity pause timeout for ActivityRecord{41b22010 com.example.jsonparsing/.JsonActivity}
05-11 12:25:34.831: I/Process(77): Sending signal. PID: 722 SIG: 3
05-11 12:25:34.831: I/dalvikvm(722): threadid=3: reacting to signal 3
05-11 12:25:34.851: I/dalvikvm(722): Wrote stack traces to '/data/anr/traces.txt'
05-11 12:25:35.041: W/NetworkManagementSocketTagger(77): setKernelCountSet(10040, 0) failed with errno -2
05-11 12:25:45.058: W/ActivityManager(77): Activity destroy timeout for ActivityRecord{41b22010 com.example.jsonparsing/.JsonActivity}
4

3 回答 3

0

这是您当前错误的根源

Your content must have a ListView whose id attribute is 'android.R.id.list'

使用ListActivity时需要一个ListViewwith this id。所以在你的activity_json.xml你需要一个ListView喜欢

<ListView
     android:id="@android:id/list"

此外,您的下一个问题将是尝试在网络上做一些事情,UI但这是一个单独的问题。这是我的一个 SO 答案,涵盖了AsyncTask. 当您遇到特定问题时,请尝试并发布。记住不要把UI东西放进去doInBackground()

于 2013-05-11T00:29:08.510 回答
0

即使您可能不喜欢在我尝试做的非绝对必要时使用外部库,但我建议您使用 gson 库进行 Jason 操作

https://code.google.com/p/google-gson/

使用此库,您只需一行代码即可将任何 Json 转换为相关的 pojo,而无需任何努力。

当然,您必须至少将网络操作放入异步任务或可运行对象中。

于 2013-05-11T00:29:31.167 回答
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://blahblah";
        //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");
                    //String course_name = c.getString("someString2");
                    //String course_semester = c.getString("someString3");

                    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));
        }
        }
}
于 2013-05-21T06:49:34.110 回答