I have json file like this:
{
"player": {
"id": "29920",
"name": "Random Name",
"matches": {
"0": {
"position": "2",
"points": "22.00"
},
"1": {
"position": "2",
"points": "22.00"
},
"2": {
"position": "2",
"points": "22.00"
},
"3": {
"position": "2",
"points": "22.00"
}
}
}
}
Where amount of matches is quite big. How to properly deserialized matches?
I have something like this:
public class PlayerInfo
{
public player player;
}
public class player
{
public int id;
public string name;
public List<matches> matches;
}
public class matches
{
public int position;
public float points;
}
but matches are empty.
I call method:
JsonConvert.DeserializeObject<PlayerInfo>(json);
The common way is to use a Dictionary<string, Match>
Matches instead of List<Match>
Data data= JsonConvert.DeserializeObject<Data>(json);
classes
public partial class Data
{
[JsonProperty("player")]
public Player Player { get; set; }
}
public partial class Player
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("matches")]
public Dictionary<string, Match> Matches { get; set; }
}
public partial class Match
{
[JsonProperty("position")]
public long Position { get; set; }
[JsonProperty("points")]
public string Points { get; set; }
}
if you need, you can still create a list instead of dictionary, but in this case your classes should be changed, you need to add an extra Num propery to Match
public partial class Data
{
[JsonProperty("player")]
public Player Player { get; set; }
}
public partial class Player
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("matches")]
public List<Match> Matches { get; set; }
[JsonConstructor]
public Player(Dictionary<string, MatchDetail> matches)
{
Matches = matches.Select(m => new Match { Num = m.Key, MatchDetail = m.Value }).ToList();
}
public Player() {}
}
public partial class Match
{
public string Num { get; set; }
public MatchDetail MatchDetail { get; set; }
}
public partial class MatchDetail
{
[JsonProperty("position")]
public long Position { get; set; }
[JsonProperty("points")]
public string Points { get; set; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.