如何将JSON解析为ListView

问题描述 投票:-5回答:1

如何在服务器或网站中将JSON解析为Android Studio中的ListView>

例如,解析此JSON文件

{
   "courses":[
      {
         "id":1,
         "course":"Русский язык"
      },
      {
        "id":2,
         "course":"English language"
      },
      {
        "id":3,
         "course":"Spanish language"
      }
   ]
}
android json algorithm listview
1个回答
0
投票

您可以通过两个步骤完成此操作:

1)创建id,course的对象列表

try {
    // Convert the String to JSON
    JSONObject jsonObject = new JSONObject(jsonString);
    JSONArray jArray = jsonObject.getJSONArray("courses");
    for (int i = 0; i < jArray.length(); i++) {
        JSONObject jObject = jArray.getJSONObject(i);

        String id = jObject.getString("id");
        String course = jObject.getString("course");
        yourList.add(new Course(id, course))

    }
} catch (JSONException e) {
    Log.e(this.getClass().getName(), "Some JSON error occurred" + e.getMessage());
}

2)编写适配器以将列表转换为ListView

private class MyAdapter extends BaseAdapter {

      // override other abstract methods here

      @Override
      public View getView(int position, View convertView, ViewGroup container) {
          if (convertView == null) {
              convertView = getLayoutInflater().inflate(R.layout.list_item, container, false);
          }

          ((TextView) convertView.findViewById(android.R.id.course))
                  .setText(getItem(position));
          return convertView;
      }
  }

获得ListView的帮助

© www.soinside.com 2019 - 2024. All rights reserved.