使用Gson在Android中使用JSON到ListView

我正在尝试将json结果放入我的Android应用程序中的ListView中.

这是我的Json:

[
    {
        "Result": "8:30,21",
        "Meeting": "Antwerp Olympics",
        "Event": "3000m",
        "Date": "30/05/2013"
    },
    {
        "Result": "008,32",
        "Meeting": "Antwerp Olympics",
        "Event": "Long Jump",
        "Date": "30/05/2013"
    },
    {
        "Result": "6,35",
        "Meeting": "Antwerp Olympics",
        "Event": "High Jump",
        "Date": "30/05/2013"
    },
    {
        "Result": "5,00",
        "Meeting": "Antwerp Olympics",
        "Event": "Discus Throw",
        "Date": "30/05/2013"
    }
]

这是我的Android代码

Gson gson = new Gson();
Result[] res = gson.fromJson(results, Result[].class);
ListView lv1 = (ListView) getView().findViewById(R.id.sampleListView);
String[] values = new String[] { }; //values
ArrayAdapter<String> files = new ArrayAdapter<String>(getActivity(),android.R.layout.list_content, values);
lv1.setAdapter(files);

通过GSON获得json结果,我用一个简单的json做到了.现在我不知道如何在listview中实现这个JSON结果.我应该如何填充String []值?

提前致谢

最佳答案
创建一个Class Named EventEntity或您的选择

import com.google.gson.annotations.SerializedName;

public class EventEntity{

    @SerializedName("Result")
    public int Result;

    @SerializedName("Meeting")
    public String Meeting;

    @SerializedName("Event")
    public String Event;

    @SerializedName("Date")
    public String Date;

    public EventEntity()
    {}
}

并将listview数据绑定代码更改为此

ListView lv1 = (ListView) getView().findViewById(R.id.sampleListView);
Gson gson = new Gson();
List<EventEntity> events = (List<EventEntity>) gson.fromJson(results, new TypeToken<EventEntity>>() {}.getType());
ArrayAdapter<EventEntity> files = new ArrayAdapter<EventEntity>(..........);
lv1.setAdapter(files);

编辑,
您应该创建自定义适配器类和行布局

public class MyCustomAdapter extends ArrayAdapter<EventEntity> {

  private final List<EventEntity> list;
  private final Activity context;

  public MyCustomAdapter (Activity context, List<EventEntity> list) {
    super(context, R.layout.rowlayout, list);
    this.context = context;
    this.list = list;
  }

  static class ViewHolder {
    protected TextView eventTitle;
    protected TextView eventDate;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    View view = null;

      LayoutInflater inflator = context.getLayoutInflater();
      view = inflator.inflate(R.layout.rowlayout, null);
      final ViewHolder viewHolder = new ViewHolder();
      viewHolder.eventTitle = (TextView) view.findViewById(R.id.label);
      viewHolder.eventDate = (TextView) view.findViewById(R.id.date);

      view.setTag(viewHolder);

     ViewHolder holder = (ViewHolder) view.getTag();
     holder.eventTitle.setText(list.get(position).Event);
     holder.eventDate.setText(list.get(position).Date);

     return view;
} 

转载注明原文:使用Gson在Android中使用JSON到ListView - 代码日志