小编mip*_*ipi的帖子

使用 JsonConverterAttribute 时自定义继承 JsonConverter 失败

我正在尝试反序列化派生类型,并且我想使用自定义属性Type来区分派生类型。

[
  {
    "Type": "a",
    "Height": 100
  },
  {
    "Type": "b",
    "Name": "Joe"
  }
]
Run Code Online (Sandbox Code Playgroud)

我找到的解决方案是创建一个自定义JsonConverter. 在ReadJson我读取Type属性并通过ToObject<T>函数实例化该类型时。一切正常,直到我使用JsonConverterAttribute. 该ReadJson方法无限循环,因为该属性也应用于子类型。

如何防止将此属性应用于子类型?

[JsonConverter(typeof(TypeSerializer))]
public abstract class Base
{
    private readonly string type;

    public Base(string type)
    {
        this.type = type;
    }

    public string Type { get { return type; } }
}

public class AType : Base
{
    private readonly int height;

    public AType(int height)
        : base("a")
    {
        this.height = …
Run Code Online (Sandbox Code Playgroud)

c# json.net

3
推荐指数
1
解决办法
4558
查看次数

标签 统计

c# ×1

json.net ×1