How do ASP.NET Web API controllers serialize a Dictionary<int, string> to JSON?

Posted: (EET/GMT+2)

 

When you return a C# object from an ASP.NET Web API controller, the ASP.NET runtime uses the Newtonsoft Json.NET library by default for the JSON serialization. When you return a Dictionary<int, string> type of object, Json.NET converts the integer keys to strings because JSON object property names must be strings.

Example controller action:

public IHttpActionResult Get()
{
    var map = new Dictionary<int, string>
    {
        [1] = "one",
        [2] = "two"
    };

    return Ok(map);
}

JSON response:

{
  "1": "one",
  "2": "two"
}

If you prefer an array of key/value pairs instead of an object with string keys, project it (modify for a more suitable type) before returning:

return Ok(map.Select(kvp => new { key = kvp.Key, value = kvp.Value }));

This yields:

[
  { "key": 1, "value": "one" },
  { "key": 2, "value": "two" }
]

This shape is sometimes easier for JavaScript clients that expect arrays. For enums as keys, add a string converter or project in a similar way. Keep it explicit and you avoid surprises on the client side. Also, my tip is to always include an example JSON output file somewhere, if it is not clear from the code how the output will look like.