0

People have asked this question before on how to Serialize/Deserialize A Dictionary with custom Key using Newtonsoft . The documentation says:

When serializing a dictionary, the keys of the dictionary are converted to strings and used as the JSON object property names. The string written for a key can be customized by either overriding ToString() for the key type or by implementing a TypeConverter. A TypeConverter will also support converting a custom string back again when deserializing a dictionary.

Everyone has posted answers on TypeConverter but no where do I see an example of overriding ToString on my custom type.

Has anyone successfully done that?

public class MyType
{
   public string Name {get;set;}
   public string ID {get;set;}
   public string Location {get;set}

   public override ToString()
  {
      // what to do here??
  }
}

public class MyClass
{
   public Dictionary<MyType, string> CustomKeyDictionary {get;set;}
}
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
user2330278
  • 67
  • 10
  • I don't think it's a matter of not being able to successfully do it, but more a matter of not wanting to do it. This is because the `ToString()` method is a general method that each object has, you're now "hijacking" that method to be able to make json serialization work the way you want to. However this will also give a different result if anywhere else in your program `ToString()` is called on an object of `MyType`, the reason people use the `ValueConverter` is because it enables you to tell the json serializer how you want to serialize an object of this class only for json serialization –  Sep 30 '19 at 12:55
  • 1
    Overriding `ToString()` will make **serialization** work but cannot be used for **deserialization**. For deserialization to work it's necessary to create a `TypeConverter` or `JsonConverter` since `ToString()` has no parsing ability (in fact the `MyType` object hasn't even been created yet at the point during deserialization that parsing would be necessary, so there's no way for any instance methods to be called). – dbc Sep 30 '19 at 16:33
  • 1
    Here is an example of using a custom JsonConverter to handle complex keys in a dictionary: [How To Serialize a class that derives from a Dictionary](https://stackoverflow.com/q/32847117/10263) – Brian Rogers Sep 30 '19 at 22:16
  • Thanks all for the comment. I already have the solution with TypeConvertor. I would have preferred a solution with ToString() and given that the documentation says it is doable I wanted to know how. my efforts to override ToString on my Types was/is not successful. Looks like either it does not work or no one knows how to achieve it :-) – user2330278 Oct 01 '19 at 13:51

0 Answers0