Issue Description

Serialization or Deserialization using ‘System.Type’ instances gives an error using System.Text.Json in .NET Core or ASP.NET Core

System.Text.Json.JsonException: ‘A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 0.’

Resolving Dataset or DataTable conversion issue in TextJson

I found this issue while Serializing System.Data.DataTable or Dataset to other types.

Resolution

I found these errors while using ‘System.Text.Json‘ in the .NET Core console application while serializing DataTable and DataSet types to Custom Object types.

I found that DataTable or DataSet conversion is currently not supported in the System.Text.Json serializer.

This feature will be supported by most probably future versions of .NET Core like .NET 5 or 6 or above version and until then, you may need to rely on a Custom converter for such conversion if needed.

Below is the codebase used which was producing the error for me.

static string ConvertDataTableToJson(DataTable dataTable)
    {
        // Convert DataTable to JSON using System.Text.Json
        
        return JsonSerializer.Serialize(dataTable, options);
    }

Similarly converting the dataset to JSON as below,


In the above example, we are sending the Table as inputs and serializing it as JSON.

static string ConvertDataSetToJson(DataSet dataSet)
    {
        // Convert DataSet to JSON using System.Text.Json
       
        return JsonSerializer.Serialize(dataSet, options);
    }

Due to these limitations, I had to turn it back to Newtonsoft(JSON.NET) usage until I got clarity on the future version.

Note- Please note my version was .NET SDK 3.1 early version when I wrote this article.

However Newtonsoft usage was straightforward to use which I finally opted for. Please see the below article for more details,

Another solution could be trying a Custom converter for such conversion.

I did attempt to write a custom converter using the steps mentioned in the article: Create a Custom Converter for serialization/deserialization, but found it to be time time-consuming process to cover all the scenarios.

As per Microsoft – Serialization and Deserialization of ‘System.Type’ instances will not be supported in the System.Text.JSON library due to security issues.

Did I miss anything else in these resolution steps?

Did the above steps resolve your issue? Please sound off your comments below!

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Please Subscribe to the blog to get a notification on freshly published blogs and best practices of software development.

Leave a Reply

Your email address will not be published. Required fields are marked *