How to use json.net(JObject/Jarray/Jtoken) and convert to class in the fastest way into a dictionary?

强颜欢笑 提交于 2019-12-10 22:14:53

问题


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

Can anyone help?

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

        ???
    }

回答1:


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

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

And then:

        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.

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.




回答2:


In my experiences, using JsonConvert is significantly faster than using JObject.Parse(). See this page for a performance comparison (on Windows Phone, but I'd imagine it would be similar on desktop), and linked from that page is an example that uses JsonConvert.



来源:https://stackoverflow.com/questions/34279454/how-to-use-json-netjobject-jarray-jtoken-and-convert-to-class-in-the-fastest-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!