我们已经定义了一些 JSON 文档,它们用作文档数据库中的存储格式,并且还通过服务总线发送。
这些使用 JSON.NET 反序列化为具体类。我现在想修改一个现有的属性来保存额外的数据(例如,目前我的一个类包含一个字符串数组,但现在我希望它是一个包含字符串和时间戳的类的数组。)
但是,我仍然需要能够反序列化旧文档格式。有没有一种方法,也许使用自定义 JsonConverter
,可以在旧文档格式出现时无缝转换为新文档格式?关于序列化,我希望所有文档都以新格式保存。
由于我被要求添加技术细节,这里有一个人为的讨论示例:
public class Document
{
public string[] Array { get; set; }
}
这会升级为:
public class Document
{
public class Entry
{
public string Value { get; set; }
public DateTime Timestamp { get; set; }
}
public Entry[] Array { get; set; }
}
在这个例子中,我们假设任何进来的旧格式文档应该以 DateTime.UtcNow
的时间戳结束。
最佳答案
在当前示例中,您可以使用 CustomCreationConverter对于入门级。实现CustomCreationConverter<Entry>
:
public class DocumentEntryCreationConverter : CustomCreationConverter<Document.Entry>
{
public override Document.Entry Create(Type objectType)
{
return new Document.Entry();
}
public override object ReadJson(
JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
{
// If this is not an object - looks like an old format
// So we need only set a value
if (reader.TokenType == JsonToken.String)
{
Document.Entry entry = this.Create(objectType);
entry.Value = reader.Value as string;
return entry;
}
else
{
// This is new format, we can recognise it as an object
Debug.Assert(
reader.TokenType == JsonToken.StartObject,
"reader.TokenType == JsonToken.StartObject");
return base.ReadJson(reader, objectType, existingValue, serializer);
}
}
}
这就是你如何将它应用到 Entry 类:
public class Document
{
[JsonConverter(typeof(DocumentEntryCreationConverter))]
public class Entry
{
public string Value { get; set; }
public DateTime Timestamp { get; set; }
}
public Entry[] Array { get; set; }
}
关于c# - 使用 JSON.NET 升级 JSON 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15970237/