user1952143
user1952143

Reputation: 155

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
  }

Upvotes: 3

Views: 8930

Answers (2)

maerics
maerics

Reputation: 156444

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());
  }
});

Upvotes: 9

BobTheBuilder
BobTheBuilder

Reputation: 19284

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.

Upvotes: 7

Related Questions