如何排序时间JsonParsing?时间、JsonParsing

2023-09-04 05:44:24 作者:今晚月亮缺席

我需要的时候从JSON提要排序

I need to sort the time from the Json feed

{
    "events":{
        "event":[
        {
        }
        ]
    }
}

谁能帮我解决这个问题?

can anyone help me to solve this?

推荐答案

我不知道你是怎么想它进行排序,如何完整的数据看起来像,但这里的想法:

I don't know how you want it to be sorted and how your full data looks like but here's the idea:

JSONArray jsonEvents = new JSONObject(json).getJSONArray("event");
JSONObject [] events = new JSONObject[jsonEvents.length()];

// fill an array with your events
for (int i = 0; jsonEvents.length(); i++) {
    events[i] = jsonEvents.getJSONObject(i);
}

// sort them
Arrays.sort(events, new Comparator<JSONObject>() {
    static final SimpleDateFormat sdfToDate = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

    public int compare(JSONObject event1, JSONObject event2) {
        return sdfToDate.parse(event1.getString("startTime")).compareTo(
            sdfToDate.parse(event2.getString("startTime"))
    }
});