在C#中使用Newtonsoft反序列化非顶层JSON数组的技术问题
Hey, let's fix this up for you! The main issue here is that your SportsModel class has the wrong type for the Data property — right now it's a string, but your JSON has an array under the "data" key, which should map to a List<SportsData> instead.
Step 1: Fix Your Model Classes
Update your C# classes to properly match the JSON structure. You can use the JsonProperty attribute to explicitly map each C# property to its corresponding JSON key (this avoids any casing mismatch issues):
public class SportsModel { [JsonProperty("success")] public bool Success { get; set; } [JsonProperty("data")] public List<SportsData> Data { get; set; } } public class SportsData { [JsonProperty("key")] public string Key { get; set; } [JsonProperty("active")] public bool Active { get; set; } [JsonProperty("group")] public string Group { get; set; } [JsonProperty("details")] public string Details { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("has_outrights")] public bool HasOutrights { get; set; } }
If you prefer not to use attributes, you can configure Newtonsoft.Json to automatically handle camelCase JSON keys with a resolver. This lets your PascalCase C# property names match the JSON's camelCase keys without extra annotations:
var serializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
Step 2: Deserialize and Access the List
Once your models are set up correctly, deserializing the JSON becomes straightforward. Use your existing code (with the settings above if you chose that path) to get the full model, then extract the List<SportsData> directly:
// Assuming 'response' is your raw JSON string SportsModel sportsModel = JsonConvert.DeserializeObject<SportsModel>(response); // If using the camelCase resolver: // SportsModel sportsModel = JsonConvert.DeserializeObject<SportsModel>(response, serializerSettings); // Now you have access to the data array as a List<SportsData> List<SportsData> sportsList = sportsModel.Data; // Example: Loop through the list to access individual items foreach (var sport in sportsList) { Console.WriteLine($"Sport Title: {sport.Title} | Group: {sport.Group}"); }
Why Your Original Code Failed
When you tried to deserialize the JSON array into a string property, Newtonsoft.Json couldn't convert the array to a string — this would either leave the Data property null or throw an error. By changing the property type to List<SportsData>, you're telling the serializer exactly how to map that JSON array to a usable C# collection.
内容的提问来源于stack exchange,提问作者Thomas Read

