我有一个清单。我正在将此列表转换为JSON
String
对象并将其发送到用户界面。
Gson gson = new Gson();
String jsonString = gson.toJson(environmentnamesList);
return jsonString;
这是我的JSON
对象。
[{"id":3272,"company_name":"HCL - Demo"},{"id":3255,"company_name":"IBM1 - Test"},{"id"
:3257,"company_name":"ECO1 - Development"},{"id":3253,"company_name":"MindSpace - Development"
},{"id":3256,"company_name":"ABC - Demo"},{"id":3258,"company_name":"CDF - Test"},
{"id":3205,"company_name":"FGR - Production"},{"id":3208,"company_name":"RFGGDDF - Production"
}]
现在我想按以下标准对此JSON
对象进行排序:
company_name
包含Production(RFGGDDF - Production)
优先考虑company_name
包含Development(MindSpace - Development)
给予第二优先权company_name
包含Demo (ABC - Demo)
给予第3优先级company_name
包含Test(IBM1 - Test)
第4优先级我希望输出看起来像这样:
[{"id":3205,"company_name":"FGR - Production"},{"id":3208,"company_name":"RFGGDDF - Production"},
{"id":3257,"company_name":"ECO1 - Development"},{"id":3253,"company_name":"MindSpace - Development"},
{"id":3272,"company_name":"HCL - Demo"},{"id":3256,"company_name":"ABC - Demo"}
,{"id":3258,"company_name":"CDF - Test"},{"id":3255,"company_name":"IBM1 - Test"}]...
我试过这样:
List<String> envTypes = Arrays.asList("Production", "Development", "Demo", "Test");
Ordering<Environment> ordering = Ordering.natural().onResultOf(----i don't know what arg i have to pass----);
Collections.sort(environmentnamesList, ordering);
答案 0 :(得分:2)
我建议在列表级别而不是json级别进行排序。
如下所示。我假设您有一个名为environment {name}的java List
,其中包含MyObject类型的元素。
您可以按以下方式对列表进行排序: -
Collections.sort(environmentnamesList, new CustomComparator());
String jsonString = gson.toJson(environmentnamesList);
您可以使用以下给出的CustomComparator: -
public class CustomComparator implements Comparator<MyObject> {
@Override
public int compare(MyObject o1, MyObject o2) {
String[] env =new String[]{"Demo","Test","Developement","Production"};
int env1=-1,env2=-1;
for(int i =0; i < env.length; i++)
{
if(env1<0 && o1.getCompanyName().contains(env[i]))
{
env1=i;
}
if(env2<0 && o2.getCompanyName().contains(env[i]))
{
env2=i;
}
}
return (env1 < env2) ? 1 :(env1 == env2)? 0: -1;
}
}