Sunday, April 12, 2015

How to return JSON objects from Web API 2

Hi All,

I was trying to return an object from web api 2.0 and i was getting the following error:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

The inner exception message was stating the following:

Type 'Newtonsoft.Json.Linq.JToken' is a recursive collection data contract which is not supported. Consider modifying the definition of collection 'Newtonsoft.Json.Linq.JToken' to remove references to itself.


Sample method:

[HttpGet]
[ResponseType(typeof(ChargifyTransaction))]      
public async Task<MyObject> GetTransactionDetails(string transactionId)

{

   MyObject obj = new MyObject();
   obj.Id=123222;
   obj.Name = "Mostafa dev";
   
   return obj;
}

The solution:

Add the following 2 lines in Global.asax file under App_Start method, This will force the web api to return Json formats and to ignore references to itself for Newtonsoft.Json dll.



 protected void Application_Start()
        {
            // Force to use Json formatter and ignore reference looping.
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);


           }


Hope this helps.

Post a Comment