简体   繁体   English

按作为参数传递的字段对其余获取请求的结果进行排序

[英]Sorting rest get request results by field passed as a parameter

I am currently working on a Rest API, in a get method which suppose to return an Array of objects in json format I now have the requirement to sort the result by a field passed as a parameter to the method. 我目前正在使用Rest API,在一个get方法中,该方法假定返回json格式的对象数组,现在我需要按作为参数传递给该方法的字段对结果进行排序。 Consider for example the object to be 例如考虑对象是

public class ExampleType {
    int firstField ; 
    String secondField ; 
}

Now according to the requirements the Rest API user should be able to pass as a parameter among other things either "firstField" or "secondField" and I should be sorting the array containing the result objects using this field. 现在,根据要求,Rest API用户应该可以作为参数传递“ firstField”或“ secondField”等参数,并且我应该使用此字段对包含结果对象的数组进行排序。

Apparently my model is not so simplistic as the example, I do have more than 15 fields which could potentially be the one that I need to sort by, so an else if statement is not a choice at this point. 显然,我的模型并不像示例中那样简单,我确实有15个以上的字段,可能是我需要排序的字段,因此,此时if语句不是一个选择。 My question is does anybody had a similar requirement for a rest api and if so how did you tackle it ? 我的问题是,有人对rest api有类似的要求吗?如果是,您如何解决呢? Or any recommendation on what could potentially by an elegant solution to my problem would be greatly appreciated. 或者,如果对解决我的问题有什么好的建议,将不胜感激。

You should create a Comparator and then use this to sort your data. 您应该创建一个Comparator ,然后使用它来对数据进行排序。

The comparators could be stored in a static map to avoid a switch/case if/else: 比较器可以存储在静态映射中,如果/其他情况,则避免开关/情况:

map.put("fieldName", Comparator.comparing(ExampleType::getFirstField));

You can combine two or more comparators using the thenComparing method. 您可以使用thenComparing方法组合两个或多个比较器。

The only other option is to create the appropriate comparators using reflection. 唯一的其他选择是使用反射创建适当的比较器。

Note: requirements of API consumers often are not requirements that should be implemented in the API itself. 注意: API使用者的要求通常不是应该在API本身中实现的要求。 You may also consider that sorting output is in fact a display problem and not something that an API needs to be concerned with. 您可能还认为排序输出实际上是显示问题,而不是API需要考虑的问题。

It depends on the situation though, if data needs to be paginated then you may have no option other than to sort at the API level. 但是,这取决于情况,如果需要对数据进行分页,则除了在API级别进行排序之外,您别无选择。

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

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