简体   繁体   English

反序列化抽象class实现.Net Core C#

[英]Deserialization abstract class implementation .Net Core C#

Short explanation: Project in Angular and.NetCore where I try to update a list of abstract classes in my backend.简短说明: Angular 和 .NetCore 中的项目,我尝试在后端更新抽象类列表。 By creating a put request I update the container model which holds the list I want to update.通过创建一个 put 请求,我更新了包含我要更新的列表的容器 model。 The frontend serialises the container model with JSON.stringify();前端用JSON.stringify();

When my put request reaches my endpoint it starts deserializing right away.当我的 put 请求到达我的端点时,它会立即开始反序列化。 And I get the exception: System.NotSupportedException: Deserialization of reference types without parameterless constructor is not supported.我得到了异常:System.NotSupportedException:不支持没有无参数构造函数的引用类型的反序列化。 Type 'Tile'.键入“平铺”。

This exception does not surprise me because the abstract class can not be instantiated.这个异常并不让我感到惊讶,因为抽象 class 无法实例化。 So I tried using a custom JsonConverter which defines when to convert to which class.所以我尝试使用自定义的 JsonConverter,它定义了何时转换为 class。 But this Converter never gets called.但是这个转换器永远不会被调用。 I have a breakpoint placed in the ReadJson method but the exception is thrown before it reaches the breakpoint.我在 ReadJson 方法中放置了一个断点,但是在到达断点之前抛出了异常。

Custom JsonConverter自定义 JsonConverter

Abstract model摘要 model

Implementation of the abstract class抽象 class 的实现

Put Endpoint放置端点

Update:更新:

So after continuing for a couple of hours I found out that my project uses System.Text.Json.Serialization for serializing the object.因此,在继续几个小时后,我发现我的项目使用 System.Text.Json.Serialization 来序列化 object。 The CostumConverter I created is a Newtonsoft.我创建的 CostumConverter 是 Newtonsoft。 That's why it probably isn't called.这就是为什么它可能不被调用的原因。 Is there a way to specify to my project which to use?有没有办法指定我的项目使用哪个? I have a startup.cs File where I think stuff like this might go.我有一个 startup.cs 文件,我认为像这样的东西可能是 go。

you can use generic type parameter, allows you to specify an arbitrary type T to a method at compile time, without specifying a concrete type in the method or class declaration.您可以使用泛型类型参数,允许您在编译时为方法指定任意类型 T,而无需在方法或 class 声明中指定具体类型。

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-type-parameters https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-type-parameters

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM