如何根据我的要求对json进行排序

时间:2015-11-25 07:00:08

标签: java json

我有一个list.i正在将此列表转换为json String对象并将其发送给ui。

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对象进行排序:

要求:

1)如果我的comapny_name包含Production(RFGGDDF - Production),则优先考虑

2)如果我的company_name包含Development(MindSpace - Development),则优先考虑。

3)如果我的company_name包含Demo(ABC - Demo)给予第三优先级

4)Id我的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"}]

3 个答案:

答案 0 :(得分:0)

我会尝试在转换为json之前对environmentnamesList进行排序。列表内的条目应具有可比性。即实现Comparable接口

编辑1:

 Gson gson = new Gson();
 // TODO: sort environmentnamesList here
 String jsonString = gson.toJson(environmentnamesList);
 return jsonString;

public class EnvironmentItem 
        implements Comparable<EnvironmentItem> {
    public int compareTo(EnvironmentItem item) {
        // TODO compare this & item 
    }
}

答案 1 :(得分:0)

我同意@ virtual-agent-07,我应该在转换为JSON之前对环境进行排序。
有很多方法可以做到这一点,我建议使用Google的Guava库。
例如:

List<Environment> environments = //...
List<String> envTypes = Arrays.asList("Production", "Development", "Demo", "Test");
Ordering<Environment> ordering = Ordering.natural().onResultOf(c -> Iterables.indexOf(envTypes, envType -> c.getCompanyName().contains(envType)));
Collections.sort(environments, ordering);

答案 2 :(得分:-1)

试试这个......

<script>
  angular.module('myapp', [])
  .controller('testCtrl', ['$scope', function($scope){

    var compareData = ["FGR - Production", "RFGGDDF - Production", "ECO1 - Development", "MindSpace - Development", "HCL - Demo", "ABC - Demo", "CDF - Test", "IBM1 - Test"];

   var 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.sort(function(objA, objB){
      return compareData.indexOf(objA.company_name) - compareData.indexOf(objB.company_name);
    });
    console.log(json);
  }]);

</script>