简体   繁体   English

从具有多个对象的字符串中反序列化 C# 中的 JSON Object

[英]Deserialize a JSON Object in C# from a string with multiple objects

I've been trying to deserialize a JSON file coming from a webpage, then putting it into a list.我一直在尝试反序列化来自网页的 JSON 文件,然后将其放入列表中。 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: 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));
    }
}

and lastly, the JSON string looks like this (forgive the picture, but it's far too long to copy and paste):最后,JSON 字符串看起来像这样(请原谅图片,但复制和粘贴太长了):

This is the JSON string这是 JSON 字符串

I, however, get a System.Text.Json.JsonException when deserializing.但是,我在反序列化时得到一个 System.Text.Json.JsonException。 Any clue as to why?关于为什么的任何线索?

Message: The JSON value could not be converted to System.Collections.Generic.List`1[Players.Player]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.

Thanks in advance, and if there is a need of further code, I'll be more than happy to add it!提前致谢,如果需要更多代码,我将非常乐意添加!

is because your class Player and Deserialize is bad string teamData = sub2.Split(@"')")[0]; AllPlayers = JsonSerializer.Deserialize<List<Player>>(teamData);是因为您的 class PlayerDeserialize是错误的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 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);
            }
        }

for more examples How deserialize Json in c#更多示例如何反序列化 c# 中的 Json

I actually managed to fix it myself by splitting the various entries and then deserializing them one by one into a Player field.实际上,我通过拆分各种条目然后将它们一一反序列化到 Player 字段中来设法自己修复它。 The result class ended up being as follows:结果 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM