5

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372

1 Answers1

12

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"
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • hi how can I set result as json object with custom key `"result" { "Microsoft": "microsoft.com", "Google": "google.com", "Facebook": "facebook.com" }` – Neo May 30 '17 at 05:27
  • 1
    @Neo create a new anonymous object with result as property name. Using example above you would return `new { result = collection }` – Nkosi May 30 '17 at 08:32
  • @Neo I added it as an answer to your last posted question. – Nkosi May 30 '17 at 08:42