如何使用自定义键将JSON反序列化为字典

时间:2015-12-27 04:17:11

标签: c# json c#-4.0 json.net json-deserialization

如何使用Json.NET并将class转换为Dictionary?字典的关键是seed["name"]文件中的json

有人可以帮忙吗?非常感谢!

示例JSON

"Seed": [
    {
        "name": "Cheetone",
        "growthrate": 1,
        "cost": 500
    },
    {
        "name": "Tortone",
        "growthrate": 8,
        "cost": 100
    }
]

我的代码

public class SoilStat
{
    [JsonProperty(PropertyName = "growthrate")]
    public int growthRate;

    [JsonProperty(PropertyName = "cost")]
    public int cost;
}

public class DataLoader : MonoSingleton<DataLoader>
{
    public string txt;
    Dictionary<string, SoilStat> _soilList = new Dictionary<string, SoilStat>();

    // error on this line
    _soilList = array.ToDictionary(t => t["name"].ToString(), t => new SoilStat { cost = (int)t["cost"], growthRate = (int)t["growthrate"] });
}

抛出异常

  

ArgumentNullException:参数不能为null。   参数名称:value   Newtonsoft.Json.Linq.JToken.EnsureValue(Newtonsoft.Json.Linq.JToken值)(在Assets / Plugins / JsonDotNet / Source / Linq / JToken.cs:349)   Newtonsoft.Json.Linq.JToken.op_Explicit(Newtonsoft.Json.Linq.JToken值)(在Assets / Plugins / JsonDotNet / Source / Linq / JToken.cs:541)   DataLoader.m__3(Newtonsoft.Json.Linq.JToken t)(在Assets / Script / Util / DataLoader.cs:112)   System.Linq.Enumerable.ToDictionary [JToken,String,SoilStat](IEnumerable 1 source, System.Func 2 keySelector,System.Func 2 elementSelector, IEqualityComparer 1 comparer)   System.Linq.Enumerable.ToDictionary [JToken,String,SoilStat](IEnumerable 1 source, System.Func 2 keySelector,System.Func`2 elementSelector)

1 个答案:

答案 0 :(得分:2)

你可能在array阵型中做错了。

假设这是您的课程(您可以删除JsonProperty s)

public class SoilStat
{
    public int GrowthRate { get; set; }
    public int Cost { get; set; }
}

然后此代码可以正常使用您的数据

//using Newtonsoft.Json.Linq;
var jsonString = "<Read the json as string>";
Dictionary<string, SoilStat> _soilList = JObject.Parse(jsonString)["Seed"]
    .ToDictionary(s => (string)s["name"], 
                  s => new SoilStat { Cost = (int)s["cost"], 
                                      GrowthRate = (int)s["growthrate"] });