I've been trying to deserialize a JSON file coming from a webpage, then putting it into a list. The code is as follows:
public async Task Update() { try{ HttpResponseMessage response = await client.GetAsync("https://understat.com/league/Serie_A"); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); string responseParsed = Regex.Replace(responseBody, @"\\x[0-9a-fA-Z]{2}", HexConvert.DecodeHex); string[] sub1 = responseParsed.Split(@"<script>"); string sub2 = sub1[4].Substring(33); string teamData = sub2.Split(@"')")[0]; AllPlayers = JsonSerializer.Deserialize<List<Player>>(teamData); foreach (Player p in AllPlayers) Console.WriteLine(p.Player_Name + "\n"); } catch(HttpRequestException e) { Console.WriteLine("\nException Caught!"); Console.WriteLine("Message :{0} ",e.Message); } }
Class Player is:
public class Player{ public string Id { get ; set; } public string Player_Name { get; set; } public string Games { get; set; } public string Time { get; set; } public string Goals { get; set; } public string xG { get; set; } public string Assists { get; set ; } public string xA { get; set; } public string Shots { get; set; } public string Key_Passes { get; set; } public string Yellow_Cards { get ; set; } public string Red_Cards { get; set; } public string Position { get; set; } public string Team_Title { get; set; } public string nPG { get; set; } public string npxG { get; set; } public string xGChain { get; set; } public string xGBuildup { get; set; } public int Cost { get; set; } public int YearsOfContract { get; set; } //public int AvgVote { get; set; } //public Club Squad { get; set; } [JsonConstructor] public Player(string id, string player_name, string games, string time, string goals, string xg, string assists, string xa, string shots, string key_passes, string yellow_cards, string red_cards, string position, string team_title, string npg, string npxg, string xgchain, string xgbuildup) { Id = id; Player_Name = player_name; Games = games; Time = time; Goals = goals; xG = xg; Assists = assists; xA = xa; Shots = shots; Key_Passes = key_passes; Yellow_Cards = yellow_cards; Red_Cards = red_cards; Position = position; Team_Title = team_title; nPG = npg; npxG = npxg; xGChain = xgchain; xGBuildup = xgbuildup; Cost = cost; YearsOfContract = yearsofcontract; } public int GetRenewalCost(){ return (Cost * (int)Math.Ceiling(0.3 + YearsOfContract*0.1)); } public int GetRidCost(){ return (Cost* (int)Math.Ceiling(YearsOfContract*0.1)); } }
and lastly, the JSON string looks like this (forgive the picture, but it's far too long to copy and paste):
I, however, get a System.Text.Json.JsonException when deserializing. Any clue as to why? Thanks in advance, and if there is a need of further code, I'll be more than happy to add it!
https://stackoverflow.com/questions/66073306/deserialize-a-json-object-in-c-sharp-from-a-string-with-multiple-objects February 06, 2021 at 11:30AM
没有评论:
发表评论