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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

But in that case, if I just serialize List<Actor> that should also give me api.Models.Actor, because .toString() will come in picture in this case as well. But serialization of List<Actor> gives me proper result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.