Reputation: 41
I'm trying to deserialize a JSON file but I'm currently stuck because of the Array "statistics".
My JSON file looks like this:
[
{
"name": "itemName",
"level": 8,
"imgUrl": "https://imgItemName.png",
"description": "itemDescription.",
"statistics": [
{
"Vitality": {
"min": 10,
"max": 13
}
}
]
}
]
My classes look like this:
public class Item
{
public string name;
public int level;
public string type;
public string imgUrl;
public string description;
public List<Statistics>statistics;
//public List<JArray> statistics;
//public Statistics[] statistics;
}
public class Statistics
{
public string Vitality;
public List<MinMax> minmax;
//public MinMax[] minMax;
}
public class MinMax
{
public string min;
public string max;
}
And this is how I'm trying to deseralize the file:
string json = System.IO.File.ReadAllText("items.json");
var listItems = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Item>>(json);
I have already tried many combinations but cannot recover the Statistics key in any case. Any help will be really appreciated :)
Upvotes: 1
Views: 144
Reputation: 324
If you are using Visual studio you can generate the C# classes bazed on Json by going to Edit-> paste special -> Paste JSON as Classes after that add the Fix the C# name convention and you should be good to go
public class Item
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("level")]
public int Level { get; set; }
[JsonProperty("imgUrl")]
public string ImgUrl { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("statistics")]
public Statistic[] Statistics { get; set; }
}
public class Statistic
{
public Vitality Vitality { get; set; }
}
public class Vitality
{
[JsonProperty("min")]
public int Min { get; set; }
[JsonProperty("max")]
public int Max { get; set; }
}
Upvotes: 0
Reputation: 51160
With the tool Json2Csharp, your model should be as below:
public class Vitality
{
[JsonProperty("min")]
public int Min { get; set; }
[JsonProperty("max")]
public int Max { get; set; }
}
public class Statistic
{
[JsonProperty("Vitality")]
public Vitality Vitality { get; set; }
}
public class Root
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("level")]
public int Level { get; set; }
[JsonProperty("imgUrl")]
public string ImgUrl { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("statistics")]
public List<Statistic> Statistics { get; set; }
}
Upvotes: 3