API返回JSON正常但JsonSerializer反序列化后值全为null求助
API反序列化后结果全为null问题排查
我调用API获取到了有效JSON数据,但使用JsonSerializer.Deserialize<Root>进行反序列化时,结果对象的所有值均为null,请求排查原因。
一、API返回的JSON数据
{ "get":"leagues", "parameters":[ ], "errors":[ ], "results":960, "paging":{ "current":1, "total":1 }, "response":[ { "league":{ "id":4, "name":"Euro Championship", "type":"Cup", "logo":"https://media-3.api-sports.io/football/leagues/4.png" }, "country":{ "name":"World", "code":null, "flag":null }, "seasons":[ { "year":2008, "start":"2008-06-07", "end":"2008-06-29", "current":false, "coverage":{ "fixtures":{ "events":true, "lineups":true, "statistics_fixtures":false, "statistics_players":false }, "standings":false, "players":false, "top_scorers":false, "top_assists":false, "top_cards":false, "injuries":false, "predictions":true, "odds":false } }, { "year":2012, "start":"2012-06-08", "end":"2012-07-01", "current":false, "coverage":{ "fixtures":{ "events":true, "lineups":true, "statistics_fixtures":false, "statistics_players":false }, "standings":false, "players":false, "top_scorers":false, "top_assists":false, "top_cards":false, "injuries":false, "predictions":true, "odds":false } }, { "year":2016, "start":"2016-06-10", "end":"2016-07-10", "current":false, "coverage":{ "fixtures":{ "events":true, "lineups":true, "statistics_fixtures":true, "statistics_players":true }, "standings":true, "players":false, "top_scorers":false, "top_assists":false, "top_cards":false, "injuries":false, "predictions":true, "odds":false } }, { "year":2020, "start":"2019-03-21", "end":"2021-07-11", "current":true, "coverage":{ "fixtures":{ "events":true, "lineups":true, "statistics_fixtures":true, "statistics_players":true }, "standings":true, "players":true, "top_scorers":true, "top_assists":true, "top_cards":true, "injuries":false, "predictions":true, "odds":false } } ] } ] }
注:原JSON末尾存在语法错误(response数组最后一个元素后多余的逗号),已修正
二、请求代码
public class LeagueService : ILeagueService { public async Task GetLeaguesFromApiAsync() { var client = new HttpClient(); var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri("-"), Headers = { { "X-RapidAPI-Key", "-" }, { "X-RapidAPI-Host", "-" }, } }; using var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); var body = await response.Content.ReadAsStringAsync(); var result = JsonSerializer.Deserialize<Root>(body); } }
三、Root类定义
public class Root { public string Get { get; set; } public List<object> Parameters { get; set; } public List<object> Errors { get; set; } public int Results { get; set; } public Paging Paging { get; set; } public List<Response> Response { get; set; } }
排查与解决要点:
修复JSON语法错误
原JSON中response数组的最后一个对象后多了一个逗号(},}),这属于无效JSON格式,System.Text.Json解析时会直接返回null。必须先修正这个错误,确保JSON格式合法。处理属性名称大小写不匹配
System.Text.Json默认区分大小写,JSON中的键是小写(如"get"、"results"),但你的Root类属性是大写开头(Get、Results),导致映射失败。有两种解决方式:- 给类属性添加
[JsonPropertyName]特性,指定对应JSON键名:public class Root { [JsonPropertyName("get")] public string Get { get; set; } [JsonPropertyName("parameters")] public List<object> Parameters { get; set; } [JsonPropertyName("errors")] public List<object> Errors { get; set; } [JsonPropertyName("results")] public int Results { get; set; } [JsonPropertyName("paging")] public Paging Paging { get; set; } [JsonPropertyName("response")] public List<Response> Response { get; set; } } - 反序列化时配置
JsonSerializerOptions,开启不区分大小写:var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; var result = JsonSerializer.Deserialize<Root>(body, options);
- 给类属性添加
补全嵌套类定义
你的Root类引用了Paging和Response类,但未提供这些类的定义。如果这些类不存在或属性映射错误,也会导致反序列化失败。需要补全所有嵌套类,确保属性与JSON键匹配:public class Paging { [JsonPropertyName("current")] public int Current { get; set; } [JsonPropertyName("total")] public int Total { get; set; } } public class Response { [JsonPropertyName("league")] public League League { get; set; } [JsonPropertyName("country")] public Country Country { get; set; } [JsonPropertyName("seasons")] public List<Season> Seasons { get; set; } } public class League { [JsonPropertyName("id")] public int Id { get; set; } [JsonPropertyName("name")] public string Name { get; set; } [JsonPropertyName("type")] public string Type { get; set; } [JsonPropertyName("logo")] public string Logo { get; set; } } public class Country { [JsonPropertyName("name")] public string Name { get; set; } [JsonPropertyName("code")] public string Code { get; set; } [JsonPropertyName("flag")] public string Flag { get; set; } } public class Season { [JsonPropertyName("year")] public int Year { get; set; } [JsonPropertyName("start")] public string Start { get; set; } [JsonPropertyName("end")] public string End { get; set; } [JsonPropertyName("current")] public bool Current { get; set; } [JsonPropertyName("coverage")] public Coverage Coverage { get; set; } } public class Coverage { [JsonPropertyName("fixtures")] public Fixtures Fixtures { get; set; } [JsonPropertyName("standings")] public bool Standings { get; set; } [JsonPropertyName("players")] public bool Players { get; set; } [JsonPropertyName("top_scorers")] public bool TopScorers { get; set; } [JsonPropertyName("top_assists")] public bool TopAssists { get; set; } [JsonPropertyName("top_cards")] public bool TopCards { get; set; } [JsonPropertyName("injuries")] public bool Injuries { get; set; } [JsonPropertyName("predictions")] public bool Predictions { get; set; } [JsonPropertyName("odds")] public bool Odds { get; set; } } public class Fixtures { [JsonPropertyName("events")] public bool Events { get; set; } [JsonPropertyName("lineups")] public bool Lineups { get; set; } [JsonPropertyName("statistics_fixtures")] public bool StatisticsFixtures { get; set; } [JsonPropertyName("statistics_players")] public bool StatisticsPlayers { get; set; } }捕获反序列化错误
可以通过捕获JsonException查看具体错误信息,帮助定位问题:try { var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; var result = JsonSerializer.Deserialize<Root>(body, options); } catch (JsonException ex) { Console.WriteLine($"反序列化错误:{ex.Message}"); }
内容的提问来源于stack exchange,提问作者alessoi1
相关产品推荐
相关产品推荐

