【问题标题】:How to deserialize a property on JSON from one type but serialize to another type with the same name?如何将 JSON 上的属性从一种类型反序列化但序列化为具有相同名称的另一种类型?
【发布时间】:2021-01-20 13:31:21
【问题描述】:

我的问题几乎可以这样回答:https://stackoverflow.com/a/24224465/454754 但是当我的属性被替换时,我真的不知道如何使它工作(即我基本上有一个新版本的对象)。

特别是我有一堂课

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

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

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

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

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

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

只要不序列化,我不介意添加新的内部/私有属性。

我想避免使用NewFee 之类的新公共财产。

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

【问题讨论】:

标签: c# .net json.net


【解决方案1】:

感谢@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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 2017-11-15
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多