简体   繁体   中英

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. 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.

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. My question is does anybody had a similar requirement for a rest api and if so how did you tackle it ? 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.

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.

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. You may also consider that sorting output is in fact a display problem and not something that an API needs to be concerned with.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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