问题
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