使用System.Text.Json.JsonSerializer的当前版本序列化DataSet [英] Serialize DataSet with current version of System.Text.Json.JsonSerializer

查看:148
本文介绍了使用System.Text.Json.JsonSerializer的当前版本序列化DataSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您对如何使用 System.Text.Json.JsonSerializer 序列化DataSet,DataTable 有任何建议吗?
当前它抛出此异常:'检测到可能的对象周期,不支持.这可能是由于循环造成的,也可能是由于对象深度大于允许的最大深度64而引起的.'

Do you have any advice on how we can serialize DataSet,DataTable with System.Text.Json.JsonSerializer ?
Currently it throws this exception : '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 64.'

推荐答案

当前在 System中不内置对 DataSet DataTable 之类的类型的支持.Text.Json (从.NET Core 3.1开始).为了能够序列化此类类型,您将需要为所需类型实现自己的 JsonConverter< T> ,并将其注册在 JsonSerializerOptions 中.为您要求的特定类型编写一个用于序列化的代码应该很容易.

There is currently no built-in support for types like DataSet and DataTable in System.Text.Json (as of.NET Core 3.1). To be able to serialize such types, you will need to implement your own JsonConverter<T> for the types you need and register it within the JsonSerializerOptions. Writing one for serialization for the particular types you asked for should be fairly easy.

这是一个应该用于序列化的示例(省略了反序列化组件):

Here's an example that should work for serialization (left out the deserialization component):

public class DataTableConverter : JsonConverter<DataTable>
{
    public override DataTable Read(ref Utf8JsonReader reader, Type typeToConvert,
        JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }

    public override void Write(Utf8JsonWriter writer, DataTable value,
        JsonSerializerOptions options)
    {
        writer.WriteStartArray();

        foreach (DataRow row in value.Rows)
        {
            writer.WriteStartObject();
            foreach (DataColumn column in row.Table.Columns)
            {
                object columnValue = row[column];

                // If necessary:
                if (options.IgnoreNullValues)
                {
                    // Do null checks on the values here and skip writing.
                }

                writer.WritePropertyName(column.ColumnName);
                JsonSerializer.Serialize(writer, columnValue, options);
            }
            writer.WriteEndObject();
        }

        writer.WriteEndArray();
    }
}

public class DataSetConverter : JsonConverter<DataSet>
{
    public override DataSet Read(ref Utf8JsonReader reader, Type typeToConvert,
        JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }

    public override void Write(Utf8JsonWriter writer, DataSet value,
        JsonSerializerOptions options)
    {
        writer.WriteStartObject();
        foreach (DataTable table in value.Tables)
        {
            writer.WritePropertyName(table.TableName);
            JsonSerializer.Serialize(writer, table, options);
        }
        writer.WriteEndObject();
    }
}

private static void DataSet_Serialization_WithSystemTextJson()
{
    var options = new JsonSerializerOptions()
    {
        Converters = { new DataTableConverter(), new DataSetConverter() }
    };

    (DataTable table, DataSet dataSet) = GetDataSetAndTable();

    string jsonDataTable = JsonSerializer.Serialize(table, options);
    // [{"id":0,"item":"item 0"},{"id":1,"item":"item 1"}]
    Console.WriteLine(jsonDataTable);

    string jsonDataSet = JsonSerializer.Serialize(dataSet, options);
    // {"Table1":[{"id":0,"item":"item 0"},{"id":1,"item":"item 1"}]}
    Console.WriteLine(jsonDataSet);

    // Local function to create a sample DataTable and DataSet
    (DataTable, DataSet) GetDataSetAndTable()
    {
        dataSet = new DataSet("dataSet");

        table = new DataTable();
        DataColumn idColumn = new DataColumn("id", typeof(int))
        {
            AutoIncrement = true
        };

        DataColumn itemColumn = new DataColumn("item");

        table.Columns.Add(idColumn);
        table.Columns.Add(itemColumn);

        dataSet.Tables.Add(table);

        for (int i = 0; i < 2; i++)
        {
            DataRow newRow = table.NewRow();
            newRow["item"] = "item " + i;
            table.Rows.Add(newRow);
        }

        dataSet.AcceptChanges();

        return (table, dataSet);
    }
}

此文档可能会提供更多指导: https://docs.microsoft.com/zh-CN/dotnet/standard/serialization/system-text-json-converters-how-to

This document might provide more guidance: https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to

这篇关于使用System.Text.Json.JsonSerializer的当前版本序列化DataSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆