简体   繁体   中英

Sorting by some of the fields in Json Object

I have a Josn file containing array of objects like :

{
    "tId": "Something",
    "StartTime": "05/29/2013 5:28:33 PM",
    "CompleteTime": "05/29/2013 5:28:33 PM",
    "Status": "success",
    "MachineName": "Machine",
},

I have to sort according to the start time and Machine Name and display only these two things to the user. If start time is same for 2 or more tasks then the result for those should be sorted according to Machine name. I am trying to convert the JsonArray which I got after parsing to a List and use custom collections.sort after that. Am I going in the right direction ? How do I modify the comparator in Collections.sort to sort according to machine name in case of same start time

  JsonArray allTasks = jsonParser.parse(reader).getAsJsonArray();

  ArrayList<String> list = new ArrayList<String>();

  if (allTasks != null) { 
     int len = allTasks.size();
     for (int i=0;i<len;i++){ 
      list.add(allTasks .get(i).toString());
     } 
  }
  for (String task : list) {
    // code to fetch just 2 fields from this task and then sort according to start time
  }

Your sorting routine will look something like this, depending on the specifics of how you do your JSON/Object mapping:

Collections.sort(myObjectList, new Comparator<MyObject>() {
  @Override
  int compare(MyObject a, MyObject b) {
    if (a.getStartTime().equals(b.getStartTime())) {
      return a.getMachineName().compare(b.getMachineName());
    }
    return a.getStartTime().compare(b.getStartTime());
  }
});

You should create a class MyObject to hold a data of one object (tId, startTime, completeTime, status, machineName).

Then, parse each JsonObject to MyObject and add it to a List<MyObject> .

Then, use Collections.sort() and a comparator to sort your list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM