Search code examples
c#jsonjson.netdeserializationjson-deserialization

C# Json.NET - Deserialize Dictionary<object, float>



I've dictionary with objects as key and a float as value. The value is the chance to instance an object instead an other.
I've to save it in a JSON (using JSON.NET - Newtonsoft) to read it later, but I can't find a solution.
N.B.: It's not a game or a Unity project
I've tried these format:

"Droppables" : [{
  {  
      "DroppableType": "LnUP",
      "SpriteFileName": "Projectile 1.png"
  },
  0.15
},
{
  {
      "DroppableType": "AnUP",
      "SpriteFileName": "Projectile 2.png"
  },
  0.15
}]
"Droppables" : [
{
    "DroppableType": "LnUP",
    "SpriteFileName": "Projectile 1.png"
},
0.15
},
{
    "DroppableType": "AnUP",
    "SpriteFileName": "Projectile 2.png"
},
0.15
]
"Droppables" : {
{
    "DroppableType": "LnUP",
    "SpriteFileName": "Projectile 1.png"
},
0.15
},
{
{
    "DroppableType": "AnUP",
    "SpriteFileName": "Projectile 2.png"
},
0.15
}

and many others, but nothing works.
Is there a manner or I've to use an other struct?
Thank you.


Solution

  • A dictionary having an object as a key has no representation in Json format. You need to use a proxy type to convert your dictionary to a more suitable structure like below :

    public class Proxy
    {
        public string DroppableType { get; set; }
        public string SpriteFileName { get; set; }
        public float Probability { get; set; }
    }
    
    // before you serialize 
    
    var result = yourDictionary.Select(t=> new Proxy { 
                    Probability = t.Value, 
                    DroppableType = t.DroppableType,
                    SpriteFileName = t.SpriteFileName 
                }).ToArray();
    
    // for deserializing it
    
    var dictionary = deserialized.ToDictionary(r=> new YourType { r.DroppableType, r.SpriteFileName  },r=>Probability);