简体   繁体   English

C# Json.NET - 反序列化字典<object, float>

[英]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.我必须将它保存在 JSON 中(使用 JSON.NET - Newtonsoft)以便稍后阅读,但我找不到解决方案。
NB: It's not a game or a Unity project注意:这不是游戏或 Unity 项目
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.谢谢你。

A dictionary having an object as a key has no representation in Json format.以对象为键的字典没有 Json 格式的表示。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM