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

如何将嵌套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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:01:21