首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用JsonDerivedType属性序列化和反序列化.NET 7中的多态对象

使用JsonDerivedType属性序列化和反序列化.NET 7中的多态对象
EN

Stack Overflow用户
提问于 2022-07-06 18:30:17
回答 1查看 381关注 0票数 0

JSON.NET (由Newtonsoft)支持复杂对象的序列化和反序列化。

我对使用System.Text.Json而不是JSON.NET很好奇,我在网上找不到一个很好的教程。

.NET 7预览支持反序列化多态对象。下面是一个使用.NET 7预览和C# 11的示例:

代码语言:javascript
复制
// _To run it you will need net7 preview and c# 11_

using System.Text.Json.Serialization;

var testPolymorphism = new TestPolymorphysm()
{
    Animals = new List<Animal>()
    {
        new Fish() {
             Id = "fish1",
             Name = "GoldFish",
             Action = new ActionSwim() { DistanceSwam = 10 }
        },
        new Dog() {
             Id = "dog1",
             Name = "Tom",
             Action = new ActionRun() { DistanceRan = 50  }
        }
    }
};

// serialize
var jsonSerialized = System.Text.Json.JsonSerializer.Serialize(testPolymorphism);
Console.WriteLine(jsonSerialized);

// deserialize
var clonePolymorphysm = System.Text.Json.JsonSerializer.Deserialize<TestPolymorphysm>(jsonSerialized);
Console.WriteLine(clonePolymorphysm);


// === MODELS ===

class TestPolymorphysm
{
    public List<Animal> Animals { get; set; } = new();
}

[JsonDerivedType(derivedType: typeof(Dog), typeDiscriminator: "foo1")]
[JsonDerivedType(derivedType: typeof(Fish), typeDiscriminator: "foo2")]
abstract class Animal
{
    public required string Id { get; set; }
    public required string Name { get; set; }
}

class Dog : Animal
{
    public required IAction Action { get; set; }
    public AnimalType ExtensionType => AnimalType.Dog;
}

class Fish : Animal
{
    public required IAction Action { get; set; }
    public AnimalType ExtensionType => AnimalType.Fish;
}

[JsonDerivedType(derivedType: typeof(ActionSwim), typeDiscriminator: "foo3")]
[JsonDerivedType(derivedType: typeof(ActionRun), typeDiscriminator: "foo4")]
interface IAction { }
class ActionSwim : IAction
{
    public required int DistanceSwam { get; set; }
}

class ActionRun : IAction
{
    public required int DistanceRan { get; set; }
}

public enum AnimalType
{
    Fish,
    Dog
}

无论如何,多亏了JsonDerivedType属性,这段代码才能工作,但我不知道它为什么工作。为什么如果我删除typeDiscriminators foo1、foo2、foo3和foo4,它就不能工作?在我使用它之前,我要确保我理解它的工作原理。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-06 18:45:15

对不起,我没有注意序列化对象。它包含:"$type": "foo1","$type": "foo2",等。

这就是反序列化器知道如何反序列化对象的原因。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72888351

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档