C#控制台应用反序列化JSON中@开头属性的问题咨询
问题修复方案
核心原因
你当前的写法存在两个问题:
- C#中属性名前加
@仅用于转义C#关键字(比如class是关键字,加@才可以作为属性名使用),并不会让JSON序列化时自动匹配带@前缀的属性名,序列化时默认会把属性名识别为class,和JSON返回的@class不匹配。 - 你的
AlertResponse实体类缺少JSON返回中存在的patchUid、policyUid两个字段(如果不需要这两个字段可以不加,不影响其他属性映射)。
修复步骤
1. 确认序列化依赖
你用到的ReadAsAsync默认使用Newtonsoft.Json(Json.NET)作为序列化器,先确保你的项目已安装Newtonsoft.Json NuGet包。
2. 修改AlertResponse实体类
使用JsonProperty特性显式指定要映射的JSON属性名:
using Newtonsoft.Json; // 引入命名空间 public class AlertResponse { // 显式指定映射JSON中的@class属性 [JsonProperty("@class")] public string Class { get; set; } // 不用再写@转义,属性名可以自定义 public string patchUid { get; set; } public string policyUid { get; set; } public string result { get; set; } public string info { get; set; } }
3. System.Text.Json序列化器适配方案
如果你的项目用的是System.Net.Http.Json扩展的序列化方法,默认使用System.Text.Json序列化器,就替换为对应特性即可:
using System.Text.Json.Serialization; // 引入命名空间 public class AlertResponse { [JsonPropertyName("@class")] public string Class { get; set; } public string patchUid { get; set; } public string policyUid { get; set; } public string result { get; set; } public string info { get; set; } }
修改完成后重新运行即可正常映射@class属性。
内容的提问来源于stack exchange,提问作者Glacierdk
相关产品推荐
相关产品推荐

