首页 > 解决方案 > 如何使用 POCO 类反序列化包含数字的 JSON 属性?

问题描述

我在Unity引擎中使用JSONUtility练习JSON反序列化。我在stackoverflow(Link)的帮助下使用POCO类解决了一些示例。我已经解决了以下JSON。使用 POCO 类中的确切名称进行链接。但是当 JSON 属性包含如下整数时。

{


"1": {
    "Armor": 1, 
    "Strenght": 1
  }, 
  "0": {
    "Armor": 1, 
    "Mana": 2, 
    "Strenght": 1, 
    "Health": 1, 
    "Power": 1
  }
}

以类似的方式解决没有成功。根据我得到的反馈,我必须使用字典。

 IEnumerator GetExampleValues()
{
    string URLss = "http://www.json-generator.com/api/json/get/bOQGnptixu?indent=2";
    WWW readjson = new WWW(URLss);
    yield return readjson;

    Debug.Log("ReadJSON"+readjson.text);


}

下面是我的 POCO 课程

using System.Collections.Generic;

[System.Serializable]
public class Exampleget  
{
    public int Power;
    public int Mana;
    public int Strenght;
    public int Armor;
    public int Health;

}

public class GetNumbers
{

    public List<Exampleget> onevalues;
}

标签: c#jsonunity3dpoco

解决方案


解决此问题的一种方法是使用 JsonExtensionData 属性

public class Exampleget  
{
    public int Power;
    public int Mana;
    public int Strenght;
    public int Armor;
    public int Health;

}

public class GetNumbers
{
    [JsonExtensionData]
    public Dictionary<string,dynamic> Values;
}

有了班级,现在你可以,

var str = @"{
        '1': {
            'Armor': 1, 
            'Strenght': 1
          }, 
          '0': {
            'Armor': 1, 
            'Mana': 2, 
            'Strenght': 1, 
            'Health': 1, 
            'Power': 1
          }
        }";

var result = JsonConvert.DeserializeObject<GetNumbers>(str);
foreach(var item in result.Values)
{
    Console.WriteLine($"For Key {item.Key},Power = {item.Value.Power}, Mana = {item.Value.Mana}, Armor = {item.Value.Armor}, Health = {item.Value.Health}");
}

输出

For Key 1,Power = , Mana = , Armor = 1, Health = 
For Key 0,Power = 1, Mana = 2, Armor = 1, Health = 1

更新

如果您想使用 DictionaryDictionary<string,Exampleget>而不是使用动态,那么您可以使用转换为 Exampleget 的附加属性。但这是以额外的序列化/反序列化为代价的,因此除非您有充分的理由坚持下去,否则不建议这样做。

public class GetNumbers
{
    [JsonExtensionData]
    public Dictionary<string,object> Values;
    [JsonIgnore]
    public Dictionary<string,Exampleget> ExamplegetDictionary=> Values.Select(x=>new KeyValuePair<string,Exampleget>(x.Key, ((object)x.Value).Cast<Exampleget>()))
                                                                      .ToDictionary(x=>x.Key,y=>y.Value);

}

public static class Extension
{
    public static T Cast<T>(this object value)
    {
        var jsonData = JsonConvert.SerializeObject(value);
        return JsonConvert.DeserializeObject<T>(jsonData);
    }
}

推荐阅读