3

I'v been able to return a HashTable from a Web Service that I setup for a .Net 2.0, but the service fails to retun a DataTable in JSON. I keep getting the following error: 'A circular reference was detected while serializing an object'. Any tips?

 [WebMethod(EnableSession = true) ]
public DataTable getSavedAddresses()
{
    DataTable dt = new DataTable();
    if (Session["ClientID"] != null)
    {
        int clientId = Convert.ToInt32(Session["ClientID"]);
        dt = Address.GetClientShippingAddresses(clientId);
    }
    return dt;

}

GreenEggs
  • 527
  • 6
  • 17

2 Answers2

1

The circular reference is likely due to DataTable having a Columns property, and each DataColumn object has a Table property.

The information in this blog post by Rick Strahl may be of help to you, perhaps.

chyne
  • 657
  • 4
  • 9
  • I think I'll just try using XML instead. – GreenEggs May 22 '09 at 21:23
  • I think this answer is suggesting that a custom serializer is needed. That's what Rick Strahl does in the blog post, first with JSON.NET, then with the built-in JavaScriptSerializer library. – Spivonious Aug 25 '17 at 17:26
0

Just a quick re-visit to this old question... I do it this way:

var header = datatable.Columns.Cast<DataColumn>().Select(r => new KeyValuePair<string, object>(r.ColumnName, r.DataType.Name));
var data = datatable.Select().AsEnumerable()
    .Select(r => r.Table.Columns.Cast<DataColumn>()
        .Select(c => new KeyValuePair<string, object>(c.ColumnName, r[c.Ordinal] is DBNull ? null : r[c.Ordinal] )
    ).ToDictionary(z=>z.Key,z=>z.Value)
);

return new DatatableRequestResponse
{
    data = data,
    header = header
};
JSobell
  • 1,825
  • 1
  • 14
  • 10