Returning dynamic key value collection in ASP.NET Web API

Wai Yan Hein picture Wai Yan Hein · Dec 11, 2016 · Viewed 8.1k times · Source

I am developing an ASP.Net Web API project. In my project, I am trying to return JSON from action in this format.

{
  "Apple": null,
  "Microsoft": null,
  "Google": 'http://placehold.it/250x250'
}

As you can see in the JSON, it is key value pairs. Both key and value are dynamic. So I tried to return NameValueCollection from action to get that format. Here is my code:

public class CompaniesController : ApiController
{
    // GET api/<controller>
    public HttpResponseMessage Get()
    {
        NameValueCollection collection = new NameValueCollection();
        collection.Add("Microsoft", "microsoft.com");
        collection.Add("Google", "google.com");
        collection.Add("Facebook", "facebook.com");
        return Request.CreateResponse(HttpStatusCode.OK, collection, "application/json");
    }
}

But then I access the action, it is returning the JSON like below.

enter image description here

As you can see, it is only returning Keys. Names are excluded. That is not the format I want. How can I fix my code to get name value pairs returned?

Answer

Nkosi picture Nkosi · Dec 12, 2016

Use Dictionary<string, object> to add key value pairs.

public class CompaniesController : ApiController {
    // GET api/<controller>
    public HttpResponseMessage Get() {
        var collection = new Dictionary<string, object>();
        collection.Add("Microsoft", "microsoft.com");
        collection.Add("Google", "google.com");
        collection.Add("Facebook", "facebook.com");
        return Request.CreateResponse(HttpStatusCode.OK, collection, "application/json");
    }
}

with application/json, the above will return

{
  "Microsoft": "microsoft.com",
  "Google": "google.com",
  "Facebook": "facebook.com"
}