4

我在 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);

详细异常:

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 declaredPropertyType, 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。

你能帮忙吗?

谢谢你。

4

1 回答 1

6

简短的回答:至少暂时无法使用 System.Text.Json 来完成。

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

解决方法: 首先,您应该检查 MS 的“从 ASP.NET Core 2.2 迁移到 3.0”文档的“Json.NET 支持”。

解决方案有 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;
    });

后:

services
    .AddMvc(options =>
    {
        options.EnableEndpointRouting = false;
    })
    .AddNewtonsoftJson()
    .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.IgnoreNullValues = true;
        options.JsonSerializerOptions.WriteIndented = true;
    });
于 2019-10-04T09:16:19.337 回答