在 ASP.NET Web API 中返回动态键值集合

Returning dynamic key value collection in ASP.NET Web API

我正在开发一个 ASP.Net Web API 项目。在我的项目中,我试图从这种格式的动作中 return JSON。

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

正如你在JSON中看到的那样,它是键值对。键和值都是动态的。因此,我尝试从操作中 return NameValueCollection 获取该格式。这是我的代码:

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");
    }
}

但随后我访问了该操作,它正在 returning JSON,如下所示。

如您所见,它只是 returning 键。名字被排除在外。那不是我想要的格式。如何修复我的代码以获取名称值对 returned?

使用Dictionary<string, object>添加键值对。

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");
    }
}

application/json,上面会return

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