You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 05:57:42