如何在C#中反序列化含任意数量Edges和Nodes的GraphQL响应
解决GraphQL查询结果反序列化Company类的错误
错误原因
你的JSON中locations是单个对象(结构为{"edges": [...]}),但Company类里将Locations定义为IEnumerable<Edge<Location>>(集合类型)。JSON序列化器无法将单个对象转换为集合,因此抛出JsonSerializationException。
解决方案
调整类结构以匹配GraphQL的Connection返回格式:
- 新增通用
Connection<T>类,用于包裹edges数组 - 修改
Company类的Locations属性类型为Connection<Location> - 修正
Edge<T>类的职责,使其对应单个edge节点
修改后的完整代码:
public class Company { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("id")] public string Id { get; set; } [JsonProperty("externalId")] public string ExternalId { get; set; } [JsonProperty("locations")] public Connection<Location> Locations { get; set; } } // 对应GraphQL的Connection结构,包含edges数组 public class Connection<T> { [JsonProperty("edges")] public IEnumerable<Edge<T>> Edges { get; set; } } // 单个Edge节点,包含具体数据的node public class Edge<T> { [JsonProperty("node")] public T Node { get; set; } } public class Location { [JsonProperty("id")] public string Id { get; set; } } public class Program { static void Main(string[] args) { var json = "{\"name\":\"ABC Company\",\"id\":\"gid://shopify/Company/12345\",\"externalId\":\"12345\",\"locations\":{\"edges\":[{\"node\":{\"id\":\"gid://shopify/CompanyLocation/12345\"}}]}}"; var company = JsonConvert.DeserializeObject<Company>(json); // 正常访问数据示例 foreach (var locationEdge in company.Locations.Edges) { Console.WriteLine($"Location ID: {locationEdge.Node.Id}"); } } }
说明
GraphQL的列表类型通常采用Connection模式返回:外层是Connection对象,内部包含edges数组,每个edge对象包含node字段存储具体数据。你之前的类结构混淆了Connection和Edge的职责,导致类型不匹配,调整后即可正常反序列化。
内容的提问来源于stack exchange,提问作者David Watson
相关产品推荐
相关产品推荐

