按Json对象中的某些字段排序 [英] Sorting by some of the fields in Json Object

查看:403
本文介绍了按Json对象中的某些字段排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下对象数组的Josn文件:

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",
},

我必须根据开始时间和机器名称进行排序,并仅向用户显示这两项内容。如果2个或更多任务的开始时间相同,则应根据机器名称对其结果进行排序。我试图将解析后得到的JsonArray转换为List并在此之后使用自定义collections.sort。我正朝着正确的方向前进吗?如何修改Collections.sort中的比较器,以便在相同的开始时间根据机器名称进行排序

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
  }


推荐答案

您的排序例程看起来像这样,具体取决于有关如何进行JSON / Object映射的详细信息:

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());
    } else {
      return a.getStartTime().compare(b.getStartTime());
    }
  }
});

这篇关于按Json对象中的某些字段排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆