JsonConvert反序列化C#对象异常:HabitProgress数值始终为默认值0
问题根源
你遇到的问题有两个核心原因:
序列化库特性不兼容
你用的是Newtonsoft.Json(JsonConvert.DeserializeObject),但模型类里标注的是System.Text.Json专属的[JsonPropertyName]特性——Newtonsoft完全不识别这个特性,导致JSON字段和模型属性无法映射,最终返回int类型的默认值0。数据类型不匹配
JSON里的current_value是浮点数(63.386128135522206),但你模型里定义的是int类型。默认情况下Newtonsoft.Json不会自动将浮点数转换为整数,这也会导致字段赋值失败。
修复方案
步骤1:替换序列化特性
把模型里的[JsonPropertyName]换成Newtonsoft.Json的[JsonProperty]特性,确保字段映射生效:
using Newtonsoft.Json; // 必须引入该命名空间 public class HabitStatus { public string Status { get; set; } public HabitProgress Progress { get; set; } } public class HabitProgress { [JsonProperty("current_value")] public int CurrentValue { get; set; } [JsonProperty("target_value")] public int TargetValue { get; set; } }
步骤2:处理类型不匹配问题
有两种可选方式:
方式一:修改属性类型为double(推荐)
保留原始数据精度,直接将CurrentValue的类型改为double,匹配JSON中的浮点数格式:[JsonProperty("current_value")] public double CurrentValue { get; set; } [JsonProperty("target_value")] public int TargetValue { get; set; } // target_value是整数,无需修改方式二:配置序列化选项强制浮点转整数
如果必须使用int类型,可以在反序列化时添加配置,让Newtonsoft自动截断浮点数为整数:var settings = new JsonSerializerSettings { Converters = { new Newtonsoft.Json.Converters.IntegerConverter() } }; var statusResponse = JsonConvert.DeserializeObject<HabitStatusJsonResponse>( File.ReadAllText("/home/ash/dev/habit-response-test.json"), settings );
补充:完善根模型类
确保HabitStatusJsonResponse与JSON根结构完全对应,避免其他字段映射失败:
public class HabitStatusJsonResponse { public List<string> Errors { get; set; } public string Message { get; set; } public HabitStatus Data { get; set; } public string Version { get; set; } public bool Status { get; set; } }
验证修复
修改后重新运行测试代码,statusResponse.Data.Progress.CurrentValue就能正确获取对应值:如果用double类型会得到63.386128135522206,用int类型并配置转换后会得到63。
内容的提问来源于stack exchange,提问作者user5405648

