Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return sorted dictionary from ASP.NET Web API

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

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

produces the following JSON:

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

The response is always ordered by a key because as I understand Dictionary<K, T> does not guarantee specific ordering. If I instead return a list of sorted KeyValuePair<K, T> Web API produces another layout:

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

which I don't want because of extra payload. So how do I return a dictionary-like key/value sequence formatted like in first sample?

like image 834
UserControl Avatar asked Nov 13 '14 13:11

UserControl


2 Answers

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

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

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

public IHttpActionResult GetStuff() 
{
    return Ok(source.Select(x => new SourceViewModel { Key = x.Code, Value = x => x.Desc})
                    .ToList());
}
like image 163
Felipe Oriani Avatar answered Nov 10 '22 10:11

Felipe Oriani


You should use the 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 don't even have a concept of sorting, it's like asking a car to sail on the water in that it would be unnatural. You might think, "but all I need to so is get them in the right order before I send them", but the client will not be able to see any order to it.

The sample above puts items in an array rather than a dictionary, and arrays do have order because they are a list. You should not worry about the extra size because this is actually very efficient already.

A different approach would be to expect the client to sort your data based on reading all the Key fields, but that's not really a polite way to send ordered data generally speaking.

like image 23
whitneyland Avatar answered Nov 10 '22 10:11

whitneyland