Returning dynamic key value collection in ASP.NET Web API
Asked Answered
E

1

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?

Estrella answered 11/12, 2016 at 15:27 Comment(2)
Use Dictionary<string,object>Ramsey
Thanks so much. it worked with Dictionary. Will you post answer? I want to upvote the answer.Estrella
R
13

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"
}
Ramsey answered 12/12, 2016 at 20:10 Comment(3)
hi how can I set result as json object with custom key "result" { "Microsoft": "microsoft.com", "Google": "google.com", "Facebook": "facebook.com" }Hendry
@Hendry create a new anonymous object with result as property name. Using example above you would return new { result = collection }Ramsey
@Hendry I added it as an answer to your last posted question.Ramsey

© 2022 - 2024 — McMap. All rights reserved.