【问题标题】:Serialize/Deserialize a class hierarchy with .NET Core System.Text.Json使用 .NET Core System.Text.Json 序列化/反序列化类层次结构
【发布时间】:2019-10-03 18:40:54
【问题描述】:

我有一个简单的类层次结构,我想使用 System.Text.Json 对其进行序列化。

有 3 个班级。基地是Shape。继承的是BoxCircle

我计划在我的前端应用程序中使用这些类作为标记联合,所以我刚刚引入了一个鉴别器属性Tag

我写了一个类型转换器,支持这个层次结构的序列化/反序列化。

我想了解的是——这是否是实现此类功能的最佳方法。事实上,序列化的输出结果非常难看(我在下面的示例中添加了注释)。无论如何,我不确定它是否以最好的方式完成。

这是我如何实现序列化/反序列化的示例:

using System;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Serialization.Theory
{
    public abstract class Shape
    {
        public abstract String Tag { get; }
    }

    public class Box : Shape
    {
        public override String Tag { get; } = nameof(Box);

        public Single Width { get; set; }

        public Single Height { get; set; }

        public override String ToString()
        {
            return $"{Tag}: Width={Width}, Height={Height}";
        }
    }

    public class Circle : Shape
    {
        public override String Tag { get; } = nameof(Circle);

        public Single Radius { get; set; }

        public override String ToString()
        {
            return $"{Tag}: Radius={Radius}";
        }
    }

    public class ShapeConverter : JsonConverter<Shape>
    {
        public override Boolean CanConvert(Type typeToConvert)
        {
            return typeToConvert == typeof(Circle) || typeToConvert == typeof(Shape);
        }

        public override Shape Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var raw = reader.GetString();
            var doc = JsonDocument.Parse(raw);
            var prop = doc.RootElement.EnumerateObject().Where(x => x.Name == "Tag").First();
            var value = prop.Value.GetString();

            switch (value)
            {
                case nameof(Circle): 
                    return JsonSerializer.Deserialize<Circle>(raw);
                case nameof(Box):
                    return JsonSerializer.Deserialize<Box>(raw);
                default:
                    throw new NotSupportedException();
            }
        }

        public override void Write(Utf8JsonWriter writer, Shape value, JsonSerializerOptions options)
        {
            if (value is Circle circle)
            {
                writer.WriteStringValue(JsonSerializer.SerializeToUtf8Bytes(circle));
            }
            else if (value is Box box)
            {
                writer.WriteStringValue(JsonSerializer.SerializeToUtf8Bytes(box));
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Keep in base class references like it's a property on another object.
            Shape origin1 = new Box { Width = 10, Height = 20 };
            Shape origin2 = new Circle { Radius = 30 };

            var settings = new JsonSerializerOptions();
            settings.Converters.Add(new ShapeConverter());

            var raw1 = JsonSerializer.Serialize(origin1, settings);
            var raw2 = JsonSerializer.Serialize(origin2, settings);

            Console.WriteLine(raw1); // "{\u0022Tag\u0022:\u0022Box\u0022,\u0022Width\u0022:10,\u0022Height\u0022:20}"
            Console.WriteLine(raw2); // "{\u0022Tag\u0022:\u0022Circle\u0022,\u0022Radius\u0022:30}"

            var restored1 = JsonSerializer.Deserialize<Shape>(raw1, settings);
            var restored2 = JsonSerializer.Deserialize<Shape>(raw2, settings);

            Console.WriteLine(restored1); // Box: Width=10, Height=20
            Console.WriteLine(restored2); // Circle: Radius=30
        }
    }
}

【问题讨论】:

  • @shadeglare,请查看相关问题中的答案(可能更简洁):stackoverflow.com/a/59744873/12509023 不支持多态(反)序列化,需要类似于您编写的转换器。添加多态序列化支持作为选择加入存在问题:github.com/dotnet/corefx/issues/38650
  • 您需要处理您的JsonDocument 以避免内存泄漏,例如通过执行using var doc = JsonDocument.Parse(raw); 了解详情,请参阅doc remarks

标签: c# json polymorphism .net-core-3.0 system.text.json


【解决方案1】:

请尝试我作为 System.Text.Json 的扩展编写的这个库以提供多态性:https://github.com/dahomey-technologies/Dahomey.Json

public abstract class Shape
{
}

[JsonDiscriminator(nameof(Box))]
public class Box : Shape
{
    public float Width { get; set; }

    public float Height { get; set; }

    public override string ToString()
    {
        return $"Box: Width={Width}, Height={Height}";
    }
}

[JsonDiscriminator(nameof(Circle))]
public class Circle : Shape
{
    public float Radius { get; set; }

    public override string ToString()
    {
        return $"Circle: Radius={Radius}";
    }
}

继承的类必须手动注册到鉴别器约定注册表,以便让框架知道鉴别器值和类型之间的映射:

JsonSerializerOptions options = new JsonSerializerOptions();
options.SetupExtensions();
DiscriminatorConventionRegistry registry = options.GetDiscriminatorConventionRegistry();
registry.RegisterConvention(new AttributeBasedDiscriminatorConvention<string>(options, "Tag"));
registry.RegisterType<Box>();
registry.RegisterType<Circle>();

Shape origin1 = new Box { Width = 10, Height = 20 };
Shape origin2 = new Circle { Radius = 30 };

string json1 = JsonSerializer.Serialize(origin1, options);
string json2 = JsonSerializer.Serialize(origin2, options);

Console.WriteLine(json1); // {"Tag":"Box","Width":10,"Height":20}
Console.WriteLine(json2); // {"Tag":"Circle","Radius":30}

var restored1 = JsonSerializer.Deserialize<Shape>(json1, options);
var restored2 = JsonSerializer.Deserialize<Shape>(json2, options);

Console.WriteLine(restored1); // Box: Width=10, Height=20
Console.WriteLine(restored2); // Circle: Radius=30

【讨论】:

    【解决方案2】:

    这对我来说很好(在 .Net 5 中):

    JsonSerializer.Serialize<object>(myInheritedObject)
    

    然后包括基类和继承类的所有属性。不知道这种方法是否有任何问题......

    【讨论】:

    • 对主对象本身非常有用,但请注意,它不会对该对象的任何基类型属性产生相同的影响。
    猜你喜欢
    • 1970-01-01
    • 2021-12-08
    • 2022-11-29
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2021-12-03
    • 2016-07-13
    • 2017-02-21
    相关资源
    最近更新 更多