[英]Deserialize a JSON Object in C# from a string with multiple objects
我一直在嘗試反序列化來自網頁的 JSON 文件,然后將其放入列表中。 代碼如下:
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 播放器是:
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));
}
}
最后,JSON 字符串看起來像這樣(請原諒圖片,但復制和粘貼太長了):
但是,我在反序列化時得到一個 System.Text.Json.JsonException。 關於為什么的任何線索?
Message: The JSON value could not be converted to System.Collections.Generic.List`1[Players.Player]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
提前致謝,如果需要更多代碼,我將非常樂意添加!
是因為您的 class Player
和Deserialize
是錯誤的string teamData = sub2.Split(@"')")[0]; AllPlayers = JsonSerializer.Deserialize<List<Player>>(teamData);
string teamData = sub2.Split(@"')")[0]; AllPlayers = JsonSerializer.Deserialize<List<Player>>(teamData);
and you are trying to deserialize a string, check this site for convert json to c# class or use visual studio, option --> Edit--> Paste Special-->Paste Json as Classes
public class Player{
public string Id { get ; set; }
//properties in your class
//
}
public async Task Update()
{
try
{
HttpResponseMessage response = await client.GetAsync("https://understat.com/league/Serie_A");
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
var resultAllPlayers = JsonSerializer.Deserialize<List<Player>>(responseBody);
return resultAllPlayers;
}
return null;
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
實際上,我通過拆分各種條目然后將它們一一反序列化到 Player 字段中來設法自己修復它。 結果 class 最終如下:
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 playersData = sub2.Split(@"')")[0];
string[] allPlayers = playersData.Split(@"},");
for(int i=0; i<allPlayers.Length-1; i++) allPlayers[i] += '}';
allPlayers[allPlayers.Length-1] = allPlayers[allPlayers.Length-1].Substring(0, allPlayers[allPlayers.Length-1].Length-1);
for(int i=0; i<allPlayers.Length; i++) AllPlayers.Add(JsonSerializer.Deserialize<Player>(allPlayers[i]));
for(int i=0; i<AllPlayers.Count; i++) Console.WriteLine(AllPlayers[i].PrintPlayer());
} catch(HttpRequestException e) {
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :" + e.Message);
} catch(JsonException e){
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message: " + e.Message);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.