【问题标题】:How parse JSON into ListView如何将 JSON 解析为 ListView
【发布时间】:2018-01-01 17:19:30
【问题描述】:

如何将来自服务器或网站的 JSON 解析成 Android Studio 中的ListView>

例如解析这个 JSON 文件

{
   "courses":[
      {
         "id":1,
         "course":"Русский язык"
      },
      {
        "id":2,
         "course":"English language"
      },
      {
        "id":3,
         "course":"Spanish language"
      }
   ]
}

【问题讨论】:

    标签: android json algorithm listview


    【解决方案1】:

    您可以分两步完成:

    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获得帮助

    【讨论】:

    • 感谢解析工作很好,但是当我创建新适配器时,我的应用程序出错了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 2020-02-28
    • 2016-03-03
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多