如何从一种类型反序列化 JSON 上的 属性 但序列化为另一种同名类型?

How to deserialize a property on JSON from one type but serialize to another type with the same name?

我的问题差不多就是这样回答的: 但是当我的 属性 被替换时,我真的不知道如何让它工作(即我基本上有一个新版本的对象)。

具体来说我有一个class

public class Something {
    public decimal? Fee { get; set;}
}

我使用 JSON.Net 序列化并存储在外部存储(数据库)中。

现在我想要一个相同的新版本class:

public class Something {
    public Fee Fee { get; set;}
}

public class Fee {
    public decimal? Amount { get; set; }
    public int Type { get; set; }
}

但是我需要能够将旧实例反序列化为新实例(如果我再次序列化它们,它们应该保存为新版本)。

我不介意添加新的 internal/private 属性,只要这些属性没有序列化即可。

我想避免的是 public 属性 之类的 NewFee 之类的。

我可能在这里遗漏了一些东西,感觉应该可以使用 JSON.Net 提供的所有钩子。

感谢@Fildor 引领我走向正确的方向。 答案看似简单,添加一个类型转换器并用转换器装饰新的 属性。

public class Something {
    [JsonConverter(typeof(FeeConverter))]
    public Fee Fee { get; set;}
}

public class Fee {
    public decimal? Amount { get; set; }
    public int Type { get; set; }
}

public class FeeConverter : JsonConverter
{

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Float || reader.TokenType == JsonToken.Integer)
        {
            var property = JValue.Load(reader);
            return new Fee() { Amount = property.Value<decimal>() };
        }

        return serializer.Deserialize(reader, objectType);
    }

    public override bool CanWrite => false;

    public override bool CanConvert(Type objectType) => false;
}