使用新的“System.Text.Json”类(Asp.net core 3.0 preview 8)序列化 System.Data.DataTable 时出现异常

Fab*_*ano 3 asp.net json system.text.json

我正在 asp.net core 3.0 preview 8 中编写一个 rest api,我试图使用新的“System.Text.Json”类序列化 System.Data.DataTable,但在 Serialize 方法中我收到异常:

不支持“System.Data.DataTable.ChildRelations”上的集合类型“System.Data.DataRelationCollection”。

使用 newtonsoft json 序列化程序可以很好地进行相同的序列化。

重现问题的示例代码:

var dt = new System.Data.DataTable("test");
dt.Columns.Add("Column1");
var ser=System.Text.Json.JsonSerializer.Serialize(dt);
Run Code Online (Sandbox Code Playgroud)

详细异常:

System.NotSupportedException HResult=0x80131515 Message=不支持“System.Data.DataTable.ChildRelations”上的集合类型“System.Data.DataRelationCollection”。Source=System.Text.Json StackTrace: 在 System.Text.Json.JsonClassInfo.GetElementType(Type propertyType, Type parentType, MemberInfo memberInfo, JsonSerializerOptions options) at System.Text.Json.JsonClassInfo.CreateProperty(Type DeclarationPropertyType, Type runtimePropertyType, Type在 System.Text.Json.JsonClassInfo.AddProperty(Type propertyType, PropertyInfo propertyInfo, Type classType, JsonSerializerOptions options) 在 System.Text.Json.JsonClassInfo..ctor(Type type, JsonSerializerOptions)选项)在 System.Text.Json。

你能帮忙吗?

谢谢你。

UNO*_*TOR 5

简短回答:至少目前无法使用 System.Text.Json 完成。

如果您想使用今天可用的 ASP.NET Core 3.0 序列化 System.Data.DataTable,请继续阅读我的文章的其余部分以获取解决方法。

解决方法: 首先,您应该检查 MS 的“Migrate from ASP.NET Core 2.2 to 3.0”文档的“Json.NET support”。

解决方法有2个步骤:

  1. 添加对“Microsoft.AspNetCore.Mvc.NewtonsoftJson”的包引用

  2. 在“services.AddMvc()”之后添加这一行“.AddNewtonsoftJson()” 以下是更改前后的 Startup.cs 示例:

前:

services
    .AddMvc(options =>
    {
        options.EnableEndpointRouting = false;
    })
    .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.IgnoreNullValues = true;
        options.JsonSerializerOptions.WriteIndented = true;
    });
Run Code Online (Sandbox Code Playgroud)

后:

services
    .AddMvc(options =>
    {
        options.EnableEndpointRouting = false;
    })
    .AddNewtonsoftJson()
    .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.IgnoreNullValues = true;
        options.JsonSerializerOptions.WriteIndented = true;
    });
Run Code Online (Sandbox Code Playgroud)

  • 如何告诉OP回到旧的JSON序列化器(他们显然已经知道它可以工作),这个问题有什么答案吗?这是一个关于如何使新的序列化器工作的问题。如果你_不能_,那么答案只是“_它无法完成_”,而不是如何使用不同序列化器的描述 (3认同)