2

I'm building an Api Controller and I need to serialize my List to JSON as my action result.but It seems that such statements doesn't work

 return Json(data, JsonRequestBehavior.AllowGet);

How can I achieve this ?

Pouyan
  • 2,849
  • 8
  • 33
  • 39
  • Could you post the entire Action Method? Does it work if you use dummy data like `var data = new List {"one", "two"};`? – Win Jul 11 '16 at 20:46

2 Answers2

2

As you mentioned that you are using WEB API, I'm assuming it has the JsonFormatter configured. With that said, the responsibility to convert you action result into a JSON is not of your action but from the Media Type Formatter chosen as part of the Content Negotiation process.

That said, it's enough for your Action to return the actual List type and the Web API Media Type formatter will take care of formatting it to JSON.

For example, let's say that data is a List<Foo> where Foo is some type that you created. It is enough for your controller action to be:

public List<Foo> GetFoo()
{
    var data = GetListOfFoo();
    return data;
}
Pedro
  • 2,300
  • 1
  • 18
  • 22
  • Very well said, I needed this in my code config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); – Pouyan Jul 13 '16 at 14:29
1

Have you tried using a JSON serializtion class?

I have had success using the ideas put forward in this article: Serializing a list to JSON

Or, if you don't want to use serialization, the example for an action result using JSON in MSDN just uses a generic list object.

Community
  • 1
  • 1
Hopeless
  • 469
  • 6
  • 16