如何按日期和时间对 jsonarray 数据进行排序并放入列表视图适配器
Posted
技术标签:
【中文标题】如何按日期和时间对 jsonarray 数据进行排序并放入列表视图适配器【英文标题】:How to sort a jsonarray data by Date & Time and put in list view adapter 【发布时间】:2016-03-06 07:41:29 【问题描述】:我的 jsonArray 数据如下:
["LeadId":4,
"CoreLeadId":0,
"CompanyId":7,
"AccountNo":"5675",
"ScheduleOn":"2015-05-11T00:00:00",
"LeadId":7,
"CoreLeadId":2,
"CompanyId":8,
"AccountNo":"sample string 4",
"ScheduleOn":"2015-12-01T15:04:23.217"]
我想按日期和时间(ScheduleOn)排序并放入列表视图。在我下方,我将我的代码片段发送到我设置适配器的位置。我们可以排序到 listItemService 中吗?请帮帮我。
JSONArray jsonArray = dpsFunctionFlow.getAllServiceDetail("1");
listItemService = new Gson().fromJson(jsonArray.toString(),
new TypeToken<List<AppointmentInfoDto>>()
.getType());
mAdapter = new AdapterAppointment(getActivity(), listItemService);
listView.setAdapter(mAdapter);
【问题讨论】:
【参考方案1】:您应该能够使用 Collections.sort(...)
传入 Comparator
来比较 2 个 AppointmentInfoDto
对象。
Collections.sort(listItemService, new Comparator<AppointmentInfoDto>()
@Override public int compare(AppointmentInfoDto l, AppointmentInfoDto r)
// Compare l.ScheduleOn and r.ScheduleOn
【讨论】:
【参考方案2】:/// Sort JSON By any Key for date
public static JSONArray sortJsonArray(JSONArray array,final String key, final boolean isCase)
List<JSONObject> jsonsList = new ArrayList<JSONObject>();
try
for (int i = 0; i < array.length(); i++)
jsonsList.add(array.getJSONObject(i));
Collections.sort(jsonsList, new Comparator<JSONObject>()
@Override
public int compare(JSONObject v_1, JSONObject v_2)
String CompareString1 = "", CompareString2 = "";
try
CompareString1 = v_1.getString(key); //Key must be present in JSON
CompareString2 = v_2.getString(key); //Key must be present in JSON
catch (JSONException ex)
// Json Excpetion handling
return CompareString1.compareTo(CompareString2);
);
catch (JSONException ex)
// Json Excpetion handling
return new JSONArray(jsonsList);
// _Sort JSON for any String Key value.........
public static JSONArray sortJsonArray(JSONArray array,final String key, final boolean isCase)
List<JSONObject> jsonsList = new ArrayList<JSONObject>();
try
for (int i = 0; i < array.length(); i++)
jsonsList.add(array.getJSONObject(i));
Collections.sort(jsonsList, new Comparator<JSONObject>()
@Override
public int compare(JSONObject v_1, JSONObject v_2)
String CompareString1 = "", CompareString2 = "";
try
CompareString1 = v_1.getString(key); //Key must be present in JSON
CompareString2 = v_2.getString(key); //Key must be present in JSON
catch (JSONException ex)
// Json Excpetion handling
return isCase ? CompareString1.compareTo(CompareString2) : CompareString1.compareToIgnoreCase(CompareString2);
);
catch (JSONException ex)
// Json Excpetion handling
return new JSONArray(jsonsList);
【讨论】:
以上是关于如何按日期和时间对 jsonarray 数据进行排序并放入列表视图适配器的主要内容,如果未能解决你的问题,请参考以下文章