0

I am using .NET 4.0, MVC 4, Web API. I have following data structure:

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

And following entry in WebApiConfig:

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

In my Controller, I am returning TopActorToMovieCount this way:

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

But the JSON output it is giving is:

{"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,"....

Why it is not giving JSON structure for object of Actor?

I am sure that I am missing something, bout couldn't figure out. I tried adding following, but it didn't work:

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

PS: When I switch to XML output, it works fine.

Arry
  • 1,630
  • 9
  • 27
  • 46

1 Answers1

1

See similar question here: Not ableTo Serialize Dictionary with Complex key using Json.net

In this case, you are using "Actor" as the Key of your dictionary. Dictionary stores key/value pairs. So when creating the JSON response, it interprets the "Actor" as a key which is converted to a string, and the "Int32" as the value thus giving you

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

because

Actor.ToString() would result in "api.Models.Actor"

Here's a link to the definition of Dictionary: https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx

Community
  • 1
  • 1
vanmeter-t
  • 63
  • 8
  • But in that case, if I just serialize List that should also give me api.Models.Actor, because .toString() will come in picture in this case as well. But serialization of List gives me proper result. – Arry Sep 06 '15 at 06:49