【发布时间】:2017-08-15 14:39:33
【问题描述】:
我有一些带有本地化文本的 .NET 类;即英文文本,对应的西班牙语文本等。我们有一个类似这样的 Locale 类:
class Locale
{
int Id;
string Abbreviation; // e.g. "en"
string Name; // e.g. "English"
static Locale FromAbbreviation(string abbreviation);
}
本地化文本存储在 IDictionary 属性中,例如
class Document
{
IDictionary<Locale, string> Content;
}
当序列化为 JSON 时,我希望它以语言环境缩写作为键,因此序列化的 Document 对象看起来像这样:
{
"content": {
"en": "English content",
"es": "Spanish content"
}
}
我需要一个 ContractResolver,它将 IDictionary<Locale, string> 对象转换为 Dictionary<string, string> 对象,在序列化期间使用 Locale.Abbreviation 属性作为键,并在反序列化时调用 Locale.FromAbbreviation() 以将键转换回 Locale对象。
我查看了 JSON.NET 文档和各种 Stackoverflow 问题,似乎没有一种简单的方法可以做到这一点(至少我找不到)。我确实找到了看起来像 straightforward way to do the same thing using a TypeConverter attribute 的东西,但我不想从我的域类中依赖 Json.NET。有没有使用 ContractResolver 的合理方法?
【问题讨论】:
标签: c# json serialization json.net