如何将嵌套JSON数组反序列化为C# List<Account>对象
解决SharpSpring API JSON反序列化嵌套数组问题
问题根源
你之前的核心错误是类定义完全不匹配API返回的JSON结构:
- JSON最外层是对象,而非数组,直接反序列化
List<Account>必然失败 - 你定义的
RootObject将result标记为字符串,但实际它是一个嵌套对象 RootAccount里的account被定义为字符串,而实际它是Account类型的数组
正确的类结构定义
严格按照JSON的嵌套层级编写对应类:
// 匹配API返回的最外层JSON对象 public class SharpSpringApiResponse { [JsonProperty("result")] public ResultContainer Result { get; set; } } // 对应result字段的嵌套对象 public class ResultContainer { [JsonProperty("account")] public List<Account> Accounts { get; set; } } // 修正属性名映射,确保和JSON字段大小写匹配 public class Account { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("ownerID")] public string OwnerId { get; set; } [JsonProperty("accountName")] public string AccountName { get; set; } // 其他属性需同样添加JsonProperty映射,保证字段名一致 }
正确的反序列化实现
先反序列化到根对象,再提取目标数组:
var request2 = new RestRequest() { Method = Method.Post, Timeout = 300000 }; var SharpSpringClient = new RestClient("https://api.sharpspring.com/pubapi/v1.2/?accountID=&secretKey="); var json = "{\"method\":\"getAccounts\",\"id\":\"zapier_getaccount\",\"params\":{\"where\":{}}}"; request2.AddStringBody(json, ContentType.Json); RestResponse response2 = SharpSpringClient.Execute(request2); // 先反序列化到根对象 var apiResponse = JsonConvert.DeserializeObject<SharpSpringApiResponse>(response2.Content); // 提取最终需要的账户列表 var accountList = apiResponse?.Result?.Accounts;
额外注意事项
- 所有JSON字段和C#属性必须通过
[JsonProperty]精准映射,避免因大小写差异导致属性值为空 - 如果API可能返回错误信息,可以在根对象中添加
[JsonProperty("error")]字段来捕获异常内容
内容的提问来源于stack exchange,提问作者ethan
相关产品推荐
相关产品推荐

