How to return a sorted dictionary from an ASP.NET web interface

I have a sequence of key / value pairs with a custom order (not by key) that I want to return:

public IHttpActionResult GetStuff() { bla-bla-bla .ToDictionary(x => x.Code, x => x.Desc); } 

outputs the following JSON:

 { "1": "ZZZ", "3": "AAA", "8": "CCC", } 

The answer is always ordered by key, because, as I understand it, Dictionary<K, T> does not guarantee a specific order. If I return, a list of sorted KeyValuePair<K, T> Web APIs will create a different layout:

 [ { "Key": 3, "Value": "AAA"}, { "Key": 8, "Value": "CCC"}, { "Key": 1, "Value": "ZZZ"}, ] 

which I don’t want because of the extra payload. So, how do I return a dictionary key / value sequence formatted as in the first example?

+6
source share
2 answers

You can use the Select() method to change the output of your dictionary to a specific ViewModel. For sample:

 public class SourceViewModel { public string Key { get; set; } public string Value { get; set; } } 

You could also use the Ok method to respond to a 200 http status code, for a sample:

 public IHttpActionResult GetStuff() { return Ok(source.Select(x => new SourceViewModel { Key = x.Code, Value = x => x.Desc}) .ToList()); } 
+2
source

You should use a second format like this (from your example):

 [ { "Key": 3, "Value": "AAA"}, { "Key": 8, "Value": "CCC"}, { "Key": 1, "Value": "ZZZ"}, ] 

The reason is that JSON dictionaries do not even have a concept of sorting, it’s like asking a car to swim in water because it would be unnatural. You might think, β€œBut all I need to do is get them in the right order before sending them,” but the customer will not be able to see any order.

In the above example, the elements are placed in an array, not a dictionary, and the arrays are in order, because they are a list. You do not have to worry about the extra size, because it is actually very effective.

Another approach would be to expect the client to sort your data based on reading all Key fields, but this is not a very polite way to send ordered data at all.

+1
source

Source: https://habr.com/ru/post/978138/


All Articles