WebAPI

时间:2015-09-03 20:15:48

标签: json asp.net-mvc-4 asp.net-web-api

我使用的是.NET 4.0,MVC 4,Web API。我有以下数据结构:

Dictionary<Actor, Int32> TopActorToMovieCount = new Dictionary<Actor, Int32>(10);

在WebApiConfig中输入后:

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));  

在我的控制器中,我以这种方式返回TopActorToMovieCount

    [HttpGet]
    public HttpResponseMessage HighestMovies()
    {            
        return Request.CreateResponse(HttpStatusCode.OK, MvcApplication.TopActorToMovieCount);
    }

但它给出的JSON输出是:

{"api.Models.Actor":137,"api.Models.Actor":125,"api.Models.Actor":99,"api.Models.Actor":96,"api.Models.Actor":83,"api.Models.Actor":82,"api.Models.Actor":81,"api.Models.Actor":79,"....

为什么它没有为Actor的对象提供JSON结构?

我确信我错过了什么,回合无法理解。我尝试添加以下内容,但它不起作用:

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));

PS:当我切换到XML输出时,它工作正常。

1 个答案:

答案 0 :(得分:1)

在此处查看类似问题:Not ableTo Serialize Dictionary with Complex key using Json.net

在这种情况下,您正在使用&#34;演员&#34;作为你词典的关键。字典存储键/值对。因此,在创建JSON响应时,它会解释&#34; Actor&#34;作为转换为字符串的键,&#34; Int32&#34;因为这样给你的价值

{"api.Models.Actor":137}{key:value}

因为

Actor.ToString()会产生"api.Models.Actor"

这是指向词典定义的链接:https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx