.NET Core 3.1中JsonSerializer反序列化简单JSON失败求助
问题分析与解决办法
嘿,这个问题我之前也碰到过,原因很明确——System.Text.Json默认只处理带有getter/setter的属性,不会自动序列化/反序列化公共字段,而你的代码里刚好都是用的字段而非属性,这就是反序列化后SyncResponse为null的核心原因。
具体问题点
你定义的Rules和SyncResponse类里的成员都是公共字段:
public class Rules { public SyncResponse SyncResponse; // 这是字段,不是属性 // ... } public class SyncResponse { public string Status; // 同样是字段 }
而JsonSerializer.Deserialize的默认行为是忽略字段,只识别带get; set;的属性,所以JSON里的内容无法映射到你的类成员上,最终导致SyncResponse为null。
两种解决方案
方案1:将字段改为属性(推荐)
这是最符合.NET编码规范的做法,给成员添加getter和setter:
namespace Whatever { public class Rules { public SyncResponse SyncResponse { get; set; } // 改为属性 public Rules Load() { var text = File.ReadAllText("/path/to/json.txt"); var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, ReadCommentHandling = JsonCommentHandling.Skip }; var result = JsonSerializer.Deserialize<Rules>(text, options); return result; } } public class SyncResponse { public string Status { get; set; } // 改为属性 } }
方案2:配置序列化器以包含字段
如果你不想修改类结构,可以在JsonSerializerOptions中开启IncludeFields选项,告诉序列化器处理字段:
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, ReadCommentHandling = JsonCommentHandling.Skip, IncludeFields = true // 添加此配置,启用字段处理 };
验证效果
不管用哪种方案,修改后再调用Rules.Load(),反序列化出来的Rules实例里的SyncResponse就会正确赋值,Status也会被设置为"success"了。
内容的提问来源于stack exchange,提问作者KBoek
相关产品推荐
相关产品推荐

