I have Updated the Question, Please see under Update 1
I am getting an error when my WebAPI tries to return the data in XML format. The JSON format works fine.
Error Details :
The 'ObjectContent`1' type failed to serialize the response body for content type
'application/xml; charset=utf-8 '.
- Detailed Error ::
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.
I somehow understood that its due to sending the deserialised object from Json.Net as the result,
return (JsonConvert.DeserializeObject(JsonString, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}));
The Problem here is that I cant create one more model class as the results will be dynamic based on the user field selection (I am already using one model class) to send the results to the user.
We want to support both XML and JSON formats and have already tried the most of the solutions mentioned in StackOverflow. Any help will be appreciated.
Update 1
I have tried to implement the solution mentioned in the link
Circular reference exception when serializing an object containing a JToken to XML in Web API
Still It shows the same error.
To make Sure I am doing the correct thing I am posting the code here.
I am getting the Jobject here.
object test = JsonHandling.generateResultSet<IEnumerable<Mytype>>
(reader,"dsfw");
This is what is doing :
public static object generateResultSet<T>(T resultList, string s)
{
try
{
string JsonString = JsonConvert.SerializeObject(resultList, new JsonSerializerSettings
{
// Formatting=Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
});
// return (JsonHelper.Deserialize(JsonString));
return (JsonConvert.DeserializeObject(JsonString, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
}));
}
catch (Exception ex)
{
throw ex;
}
}
Here is my Final Result Set Class Post the Modifications mentioned in the solution
public class PagedResults<T>
{
/// <summary>
/// The page number this page represents.
/// </summary>
///
public int? OffSet { get; set; }
/// <summary>
/// The size of this page.
/// </summary>
public int? Limit { get; set; }
// /// <summary>
// /// The total number of pages available.
// /// </summary>
//// public int TotalNumberOfPages { get; set; }
/// <summary>
/// The total number of records available.
/// </summary>
public int TotalNumberOfRecords { get; set; }
/// <summary>
/// The URL to the next page - if null, there are no more pages.
/// </summary>
public string NextPageUrl { get; set; }
/// <summary>
/// The URL to the Previous page - if null, there are no more pages.
/// </summary>
public string PrevPageUrl { get; set; }
/// <summary>
/// The URL to the Current page page - if null, there are no more pages.
/// </summary>
public string CurrentPageUrl { get; set; }
/// <summary>
/// The records this page represents.
/// </summary>
[XmlIgnore]
[JsonProperty]
public object Results { get; set; }
[XmlAnyElement("Results")]
[JsonIgnore]
public XElement ResultsXml
{
get
{
return JsonExtensions.SerializeExtraDataXElement("Results", Results);
}
set
{
Results = JsonExtensions.DeserializeExtraDataXElement("Results", value);
}
}
/// <summary>
/// This Method creates the paged result set
/// </summary>
/// <typeparam name="TReturn">Type of the model class that has been passed</typeparam>
/// <param name="results">Reults returned by the DB</param>
/// <param name="offset">Rows to offset </param>
/// <param name="limit">Total number of the rows</param>
/// <param name="req">HTTPrequest obejct </param>
/// <param name="routeName">The Name of the rouote from the route collections</param>
/// <returns></returns>
public PagedResults<TReturn> CreatePagedResults<TReturn>(object results,int? offset,int? limit,HttpRequestMessage req,string routeName)
{
try
{
var skipAmount = offset;
var totalNumberOfRecords = 1000;
var urlHelper = new UrlHelper(req);
var prevLink = offset > 0 ? urlHelper.Link(routeName, new { offset = offset - 1, limit = limit }) : "";
var nextLink = (offset + limit) < totalNumberOfRecords - 1 ? urlHelper.Link(routeName, new { offset = offset + limit, limit = limit }) : "";
var currLink = urlHelper.Link(routeName, new { offset = offset, limit = limit });
return new PagedResults<TReturn>
{
Results = results,
OffSet = offset,
Limit = limit,
TotalNumberOfRecords = totalNumberOfRecords,
NextPageUrl = nextLink,
PrevPageUrl = prevLink,
CurrentPageUrl = currLink
};
}
catch(Exception ex)
{
throw ex;
}
}
}
If I Comment
Results = results It works but thats what want to include in result.
Final Return :
PagedResults<MyType> result = new PagedResults<MyType>();
result = result.CreatePagedResults<MyType>(test, offset, limit,
Request, "jkewgfewg");
return Ok(result);
I have added the JsonExtensions as mentioned there