如何提取JSON中LocationLicense并转换为List<LocationLicense>
问题分析与解决方案
首先你的原始JSON存在语法错误——外层多了一对冗余的大括号,这会直接导致反序列化异常或结构解析错误,这是agentobj.LocationLicense返回null的核心原因之一。同时代码中使用.Result阻塞异步调用的写法也不规范,需一并修正。
步骤1:修正JSON格式
后端返回的正确JSON应该去掉外层多余的大括号,结构如下:
{ "ResponseXML": null, "Number": null, "RecordType": { "Type": "Location" }, "LocationLicense": [ { "CompanyName": "NGM", "CompanyCode": "000", "STADesc": "Arizona", "STACode": "02", "PostalAbbr": "AZ", "LICNumber": "0" }, { "CompanyName": "MSA Insurance Co of SC", "CompanyCode": "004", "STADesc": "Arizona", "STACode": "02", "PostalAbbr": "AZ", "LICNumber": "0" } ] }
如果后端无法修改返回格式,可在代码中先去除外层冗余括号:
obj = obj.Trim().TrimStart('{').TrimEnd('}');
步骤2:正确提取LocationLicense并转换为List<LocationLicense>
方案一:修正Dynamic用法(不推荐,无编译检查)
var resStr = await _client.PostAsync(_uri, new StringContent(Req_json_data, Encoding.Default, "application/json")); // 用await替代.Result,避免线程阻塞/死锁 var obj = await resStr.Content.ReadAsStringAsync(); _log.Debug(callingApp + " returned: " + obj); // 处理后端返回的冗余外层括号 obj = obj.Trim().TrimStart('{').TrimEnd('}'); dynamic agentobj = JsonConvert.DeserializeObject(obj); // 现在可正常访问LocationLicense节点 List<LocationLicense> licenseList = JsonConvert.DeserializeObject<List<LocationLicense>>( JsonConvert.SerializeObject(agentobj.LocationLicense) );
方案二:强类型反序列化(推荐,安全且易维护)
首先定义对应实体类:
public class RecordType { public string Type { get; set; } } public class LocationLicense { public string CompanyName { get; set; } public string CompanyCode { get; set; } public string STADesc { get; set; } public string STACode { get; set; } public string PostalAbbr { get; set; } public string LICNumber { get; set; } } public class LicenseResponse { public object ResponseXML { get; set; } public object Number { get; set; } public RecordType RecordType { get; set; } public List<LocationLicense> LocationLicense { get; set; } }
然后修改业务代码:
var resStr = await _client.PostAsync(_uri, new StringContent(Req_json_data, Encoding.Default, "application/json")); var obj = await resStr.Content.ReadAsStringAsync(); _log.Debug(callingApp + " returned: " + obj); // 处理冗余外层括号 obj = obj.Trim().TrimStart('{').TrimEnd('}'); // 直接反序列化为强类型模型 LicenseResponse response = JsonConvert.DeserializeObject<LicenseResponse>(obj); List<LocationLicense> licenseList = response.LocationLicense;
关键注意事项
- 必须先修正JSON的语法错误,否则所有反序列化操作都会失效;
- 异步操作禁止使用
.Result,改用await避免线程阻塞问题; - 强类型反序列化能在编译期发现字段名拼写错误,比dynamic更可靠,优先使用。
内容的提问来源于stack exchange,提问作者WorkJ
相关产品推荐
相关产品推荐

