如何使用json.net(JObject / Jarray / Jtoken)并以最快的方式将类转换为字典?

时间:2015-12-15 01:14:06

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

如何使用json.net(JObject / Jarray / Jtoken)并以最快(性能)的方式将类转换为字典?字典的关键是看" name"在json文件中

有人可以帮忙吗?

非常感谢!

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


    public class SoilStat
    {
        public int growthRate;
        public int cost;
    }

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

        JObject rawJson = JObject.Parse(txt);

        ???
    }

2 个答案:

答案 0 :(得分:2)

执行所需操作的一种简单方法是使用SelectTokens选择您感兴趣的JSON部分,然后只反序列化这些位。因此:

        var rawJson = JObject.Parse(txt);
        var _soilList = rawJson.SelectTokens("Seed[*]").ToDictionary(t => t["name"], t => t.ToObject<SoilStat>());

更复杂的解决方案是创建DTO objects进行反序列化,然后将它们映射到所需的类:

public class NamedSoilStat : SoilStat
{
    public string name { get; set; }
}

public class RootObject
{
    public RootObject() { this.Seed = new List<NamedSoilStat>(); }
    public List<NamedSoilStat> Seed { get; set; }
}

然后:

        var root = JsonConvert.DeserializeObject<RootObject>(txt);
        var _soilList = root.Seed.ToDictionary(t => t.name, t => new SoilStat { cost = t.cost, growthRate = t.growthRate });

至于哪个更高效,您需要test for yourself

顺便提一下,如果您的txt JSON字符串来自文件并且很大,则应考虑将其流式传输而不是将其读入中间字符串。请参阅Performance Tips: Optimize Memory Usage

答案 1 :(得分:1)

根据我的经验,使用JsonConvert比使用JObject.Parse()要快得多。请参阅this page for a performance comparison(在Windows Phone上,但我认为它在桌面上类似),并且从该页面链接的是an example that uses JsonConvert