使用Newtonsoft反序列化Imgur API返回JSON时List类型适配错误如何解决
Imgur API JSON响应反序列化解决方案
错误根因
该报错的核心原因是反序列化目标类型中,对应JSON外层data字段的属性被定义为了List<string>类型,但实际返回的JSON中data为单个对象结构,类型不匹配导致反序列化失败。
适配实体类定义
using System.Collections.Generic; using Newtonsoft.Json; // 外层通用响应结构 public class ImgurBaseResponse<T> { [JsonProperty("data")] public T Data { get; set; } [JsonProperty("success")] public bool Success { get; set; } [JsonProperty("status")] public int Status { get; set; } } // 对应data内的图片信息结构 public class ImgurImageInfo { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("datetime")] public int Datetime { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("animated")] public bool Animated { get; set; } [JsonProperty("width")] public int Width { get; set; } [JsonProperty("height")] public int Height { get; set; } [JsonProperty("size")] public int Size { get; set; } [JsonProperty("views")] public int Views { get; set; } [JsonProperty("bandwidth")] public long Bandwidth { get; set; } [JsonProperty("vote")] public string Vote { get; set; } [JsonProperty("favorite")] public bool Favorite { get; set; } [JsonProperty("nsfw")] public bool? Nsfw { get; set; } [JsonProperty("section")] public string Section { get; set; } [JsonProperty("account_url")] public string AccountUrl { get; set; } [JsonProperty("account_id")] public int? AccountId { get; set; } [JsonProperty("is_ad")] public bool IsAd { get; set; } [JsonProperty("in_most_viral")] public bool InMostViral { get; set; } [JsonProperty("has_sound")] public bool HasSound { get; set; } [JsonProperty("tags")] public List<string> Tags { get; set; } [JsonProperty("ad_type")] public int AdType { get; set; } [JsonProperty("ad_url")] public string AdUrl { get; set; } [JsonProperty("edited")] public string Edited { get; set; } [JsonProperty("in_gallery")] public bool InGallery { get; set; } [JsonProperty("deletehash")] public string DeleteHash { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("link")] public string Link { get; set; } }
反序列化代码示例
// jsonStr为接口返回的原始JSON字符串 var result = JsonConvert.DeserializeObject<ImgurBaseResponse<ImgurImageInfo>>(jsonStr); // 取值示例 if (result.Success && result.Status == 200) { var imageLink = result.Data.Link; var deleteHash = result.Data.DeleteHash; }
实现逻辑说明
- 外层使用泛型通用响应结构,适配Imgur所有接口的统一外层返回格式,不同接口仅需替换泛型参数即可,无需重复定义外层字段。
- 实体类属性通过
JsonProperty属性和JSON字段名严格映射,可空字段使用可空类型声明,避免空值导致的反序列化异常。 tags字段对应JSON中的空数组,定义为List<string>类型即可正常反序列化。- 反序列化时直接指定强类型参数,Newtonsoft会自动完成字段映射和赋值,无需额外配置。
内容的提问来源于stack exchange,提问作者Jackk1337
相关产品推荐
相关产品推荐

