0

我正在从以下 url 解析 json

http://www.kaverisoft.com/careers/assignments/android/a1.php

使用以下代码

公共类 MainActivity 扩展 ListActivity {

/** Called when the activity is first created. */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    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://www.kaverisoft.com/careers/assignments/android/a1.php");
        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;
}

}

logcat 显示未找到 org.json.JSONException 值文本

但我无法将任何数据填充到 listview,但如果我使用直接 json 格式的 url,我可以获得填充数据,请帮忙。

输出如下图所示。

请帮我解决这个问题。

4

1 回答 1

1

据我所知,列表中有 3 种对象:相机、书籍和音乐。对于它们中的每一个,您都必须使用不同的解析。首先,您应该检测数组的当前元素是什么类型的对象。

例如:

if (jo.has("book")) {
  JSONObject jsonBook = jo.getJSONObjcejt("book");
  // continue with parsing book stuff
} else if (jo.has("camera"){
  // same, but for camera
} else if (jo.has("music") {
  // same, but for music
}

然后你可以用你解析的书籍、音乐和相机对象填充列表。如果您想要更智能的解析,请查看gson

于 2012-08-22T17:47:02.027 回答