Json.NET - ContractResolver to serialize dictionary with non-primitive keys

Viewed 1402

I have some .NET classes with localized text; i.e. text in English, corresponding text in Spanish, etc. We have a Locale class that looks something like this:

class Locale
{
   int Id;
   string Abbreviation; // e.g. "en"
   string Name;         // e.g. "English"

   static Locale FromAbbreviation(string abbreviation);
}

Localized text is stored in IDictionary properties, something like

class Document
{
   IDictionary<Locale, string> Content;
}

When serializing to JSON, I would like this to be keyed by locale abbreviation, so a serialized Document object would look something like this:

{
   "content": {
      "en": "English content",
      "es": "Spanish content"
   }
}

I need a ContractResolver that converts an IDictionary<Locale, string> object to a Dictionary<string, string> object, using the Locale.Abbreviation property as the key during serialization, and calling Locale.FromAbbreviation() on deserialization to convert the key back to a Locale object.

I have looked at the JSON.NET documentation and various Stackoverflow questions, and there does not seem to be an easy way to do this (at least I can't find it). I did find what looks like a straightforward way to do the same thing using a TypeConverter attribute, but I would rather not take a dependence on Json.NET from my domain classes. Is there a reasonable way to do this using a ContractResolver?

1 Answers
Related