C#中JSON反序列化嵌套列表返回null的问题排查
问题分析与解决
核心问题
1. JSON结构与C#类映射完全不匹配
你的JSON里,ClientAddress对应的是直接包含firstLine和city的对象数组,但你的C#类结构做了多层嵌套:
AddressRequest的ClientAddress定义为List<ClientAddress>ClientAddress类又嵌套了List<Address>
这种结构和JSON的扁平结构完全不匹配,导致反序列化时无法匹配到正确属性,生成的对象全为null。
2. JSON存在重复键(非标准但Newtonsoft.Json会处理)
标准JSON不允许重复键名,但Newtonsoft.Json默认会将重复键对应的数组元素合并,所以你会得到计数为4的列表,只是因为类映射错误才全是null。
修正方案
步骤1:修正C#类结构
改成和JSON匹配的扁平结构:
using Newtonsoft.Json; using System; using System.Collections.Generic; namespace ConsoleApp1 { class Program { static void Main(string[] args) { var jsonData = "{\"ClientAddress\":[{\"firstLine\":\"123roadone\",\"city\":\"London\"},{\"firstLine\":\"456roadtwo\",\"city\":\"LosAngeles\"}],\"ClientAddress\":[{\"firstLine\":\"92kingsroad\",\"city\":\"Dublin\"},{\"firstLine\":\"34aJimRoad\",\"city\":\"NewYork\"}]}"; var resultSet = JsonConvert.DeserializeObject<AddressRequest>(jsonData); // 此时resultSet.ClientAddress会包含4个非null的Address对象 Console.ReadLine(); } } class AddressRequest { [JsonProperty("ClientAddress")] public List<Address> ClientAddress { get; set; } } class Address { [JsonProperty("firstLine")] public string FirstLine { get; set; } [JsonProperty("city")] public string City { get; set; } } }
步骤2:验证结果
修正后,Newtonsoft.Json会自动合并两个ClientAddress数组的元素,最终resultSet.ClientAddress会有4个Address对象,每个对象的FirstLine和City都会正确赋值。
额外说明
如果需要严格禁止解析带重复键的JSON,可以配置序列化参数:
var settings = new JsonSerializerSettings { DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error }; // 此时反序列化重复键的JSON会直接抛出异常 var resultSet = JsonConvert.DeserializeObject<AddressRequest>(jsonData, settings);
内容的提问来源于stack exchange,提问作者Aiden
相关产品推荐
相关产品推荐

