如何使用json.net(JObject / Jarray / Jtoken),并以最快的方式转换成类到字典? [英] How to use json.net(JObject/Jarray/Jtoken) and convert to class in the fastest way into a dictionary?

查看:6632
本文介绍了如何使用json.net(JObject / Jarray / Jtoken),并以最快的方式转换成类到字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to use json.net(JObject/Jarray/Jtoken) and convert to class in the fastest(performance) way into a dictionary? the key of the dictionary is the sees "name" in the json file

任何人都可以帮助?

感谢alot!

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);

        ???
    }


推荐答案

您想使用 SelectTokens 选择您感兴趣的JSON部分,然后对这些位进行反序列化。因此:

A simple way to do what you want is to use SelectTokens to pick out the portions of JSON of interest to you, then just deserialize those bits. Thus:

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

一个更复杂的解决方案是创建 DTO对象进行反序列化,然后将它们映射到您需要的类:

A more complex solution would be to create DTO objects for deserialization then map them to your desired classes:

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 });

至于哪个更高效,您需要自己测试

As to which is more performant, you would need to test for yourself.

$ c> txt JSON字符串来自一个文件,并且很大,你应该考虑将它流化,而不是将其读入一个中间字符串。请参阅性能提示:优化内存使用

Incidentally, if your txt JSON string is coming from a file, and is large, you should consider streaming it in rather than reading it into an intermediate string. See Performance Tips: Optimize Memory Usage.

这篇关于如何使用json.net(JObject / Jarray / Jtoken),并以最快的方式转换成类到字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆