简体   繁体   English

按 Json 对象中的一些字段排序

[英]Sorting by some of the fields in Json Object

I have a Josn file containing array of objects like :我有一个包含对象数组的 Josn 文件,例如:

{
    "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.如果 2 个或更多任务的开始时间相同,则应根据机器名称对这些任务的结果进行排序。 I am trying to convert the JsonArray which I got after parsing to a List and use custom collections.sort after that.我正在尝试将解析后得到的 JsonArray 转换为 List 并在此之后使用自定义 collections.sort 。 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如何修改 Collections.sort 中的比较器以在相同开始时间的情况下根据机器名称进行排序

  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:您的排序例程将如下所示,具体取决于您如何进行 JSON/对象映射:

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).您应该创建一个MyObject类来保存一个对象的数据(tId、startTime、completeTime、status、machineName)。

Then, parse each JsonObject to MyObject and add it to a List<MyObject> .然后,将每个JsonObject解析为MyObject并将其添加到List<MyObject>

Then, use Collections.sort() and a comparator to sort your list.然后,使用Collections.sort()和比较器对列表进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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