如何用json填充ListView(TwoWayView)?

时间:2015-06-03 01:12:45

标签: android json listview

我在apps数据文件夹中保存了一个json,我想用它来填充列表视图。

json结构是基本的:

{
    "someList": [
        {
            "first": "First Item"
            "second": "Second Item"
        },
        {
            "first": "Third Item",
            "second": "Fourth Item"
        },
        {
            "first": "Fifth Item",
            "second": "Sixth Item"
        }
    ]
}

我只是用

设置了一个硬编码文本
viewHolder.first.setText("First Item");
viewHolder.second.setText("Second Item");

有没有办法让它从存储的json文件中检索数据?

2 个答案:

答案 0 :(得分:2)

简短的回答是肯定有办法。

以下是步骤:

  1. 从目录

    加载文件
    InputStream is = getResources().openRawResource(R.raw.json_file);
    Writer writer = new StringWriter();
    char[] buffer = new char[1024];
    try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
           writer.write(buffer, 0, n);
       }
    } finally {
        is.close();
    }
    String jsonString = writer.toString();
    
  2. 将此转换为JSON,您可以通过

    JSONObject jsonObject = new JSONObject(jsonString);
    JSONArray jsonArray = jsonObject.getJSONArray("someList");
    
  3. 现在枚举列表中的项目并将它们添加到ViewHolder

    for(int i=0;i<jsonArray.length();i++){
         JSONObject curr = jsonArray.getJSONObject(i);
         viewHolder.first.setText(curr.getString("first"))
         viewHolder.second.setText(curr.getString("second"))
         //...now add each viewholder as an object and you're done
    }
    

答案 1 :(得分:0)

您需要使用Java JSONObjectJSONArray手动解析 json ,或者使用 google https://github.com/google/gson