使用Newtonsoft.Json反序列化键值对JSON转List<Record>报错咨询
错误原因
报错的根本原因是待反序列化的JSON为对象结构(外层由{}包裹,内部是键值对集合),而List<Record>对应的是JSON数组结构(外层由[]包裹,内部是独立元素集合),两者结构不匹配导致反序列化失败。
解决方案
方案1:用字典接收后转换(推荐,实现成本最低)
你的JSON本质是字符串类型的键值对映射,可直接反序列化为Dictionary<string, string>,如果需要使用自定义的Record类集合,再做一次转换即可:
// 读取接口返回内容 string apiResponse = response.Content.ReadAsStringAsync().Result; // 直接反序列化为字典 var translationDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(apiResponse); // 转换为Record集合 List<Record> drupalRecords = translationDict .Select(kv => new Record { Key = kv.Key, Value = kv.Value }) .ToList();
方案2:自定义JsonConverter直接反序列化为List
如果你不想额外做类型转换步骤,可以自定义JsonConverter适配反序列化逻辑:
- 先定义Converter类:
public class RecordListConverter : JsonConverter<List<Record>> { public override List<Record> ReadJson(JsonReader reader, Type objectType, List<Record> existingValue, bool hasExistingValue, JsonSerializer serializer) { // 加载JSON对象 JObject jObject = JObject.Load(reader); // 遍历所有属性转换为Record对象 return jObject.Properties() .Select(p => new Record { Key = p.Name, Value = p.Value.ToString() }) .ToList(); } public override void WriteJson(JsonWriter writer, List<Record> value, JsonSerializer serializer) { // 序列化逻辑按需实现,仅反序列化可抛出未实现异常 throw new NotImplementedException(); } }
- 反序列化时指定Converter即可:
string apiResponse = response.Content.ReadAsStringAsync().Result; drupalRecords = JsonConvert.DeserializeObject<List<Record>>(apiResponse, new RecordListConverter());
内容的提问来源于stack exchange,提问作者user1428798
相关产品推荐
相关产品推荐

