0

I would like to serialize Dictionary with complex key to JSON by serializing it as a list of KeyValuePair and deserialize it back to dictionary using Json.Net's JsonConverter.

I use this Dictionary as a transfer object's property:

public class TransferObject
{
    public string property1 {get;set}
    ...
    public Dictionary<Product,int> Products {get;set;}
}

At the end I would like to do something like this:

var jsonResult = JsonConvert.Serialize(transferObject, new DictionaryConverter())

and

var transferObject = JsonConvert.Deserialize<TransferObject>(json, DictionaryConverter())

How to implement DictionaryConverter that will convert Dictionary to list of KeyValuePair? ( I have tried, but i cannot deserialize it back) Is it good idea to convert it do list of KVP? Or maybe there is a better way to serialize Dictionary with complex key to JSON?

Thank you for your time.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Bartek Chyży
  • 521
  • 9
  • 25
  • Bart, what error message are you getting when you deserialize (or what is your result)? You shouldn't need to do anything special to do this. – Erik Philips Feb 25 '19 at 20:24
  • Thank you for response. Will post the code soon. – Bartek Chyży Feb 25 '19 at 20:52
  • Here is the converter code: https://pastebin.com/6vRR1y9M – Bartek Chyży Feb 25 '19 at 21:22
  • 1) Can you [edit] your question to include the code in the question? 2) If you are trying to serialize the dictionary as an array, did you see [Serialize dictionary as array (of key value pairs)](https://stackoverflow.com/q/12751354/3744182) or [How can I serialize/deserialize a dictionary with custom keys using Json.Net?](https://stackoverflow.com/q/24681873/3744182)? [Not ableTo Serialize Dictionary with Complex key using Json.net](https://stackoverflow.com/q/24504245/3744182) might also help. – dbc Feb 26 '19 at 23:27

0 Answers0