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;

}

2 Answers 2

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.

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

2 Comments

I think I'll just try using XML instead.
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.
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
};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.