System.Text.Json无法正确反序列化对象,如何修复该问题?
修复System.Text.Json无法反序列化对象的问题
你的问题核心原因是:Person类使用的是字段(field)而非属性(property)。System.Text.Json默认仅处理类的属性,而Newtonsoft.Json默认会兼容字段,这导致了两者的反序列化表现差异。
以下是几种可行的修复方案:
方案1:将字段改为属性(推荐)
这是符合C#编码规范的标准做法,修改Person类定义即可:
public class Person { public string Name { get; set; } public string Role { get; set; } }
修改后无需额外配置,System.Text.Json就能正常完成反序列化。
方案2:配置System.Text.Json支持字段序列化
如果无法修改原有类结构,可以通过JsonSerializerOptions显式开启字段支持:
var options = new JsonSerializerOptions { IncludeFields = true }; var personText = JsonSerializer.Deserialize<Person>(jsonElement.GetRawText(), options);
方案3:直接反序列化JsonElement(更高效)
既然已经解析得到JsonElement,无需再转换为原始字符串,直接反序列化JsonElement能避免额外的字符串操作,提升性能:
var options = new JsonSerializerOptions { IncludeFields = true }; var personText = JsonSerializer.Deserialize<Person>(jsonElement, options);
修复后的完整示例代码
using System; using System.Text.Json; using Newtonsoft.Json; public class Person { public string Name; public string Role; } public class Program { public static void Main() { string json = """{"Name":"John","Role":"Software Engineer"}"""; using JsonDocument doc = JsonDocument.Parse(json); JsonElement jsonElement = doc.RootElement; // 使用方案3的高效写法 var options = new JsonSerializerOptions { IncludeFields = true }; var personText = JsonSerializer.Deserialize<Person>(jsonElement, options); Console.WriteLine($"from System.Text.Json {personText.Role}"); var personNewton = JsonConvert.DeserializeObject<Person>(jsonElement.GetRawText()); Console.WriteLine($"from Newtonsoft.Json {personNewton.Role}"); } }
修复后的输出
from System.Text.Json Software Engineer from Newtonsoft.Json Software Engineer
内容的提问来源于stack exchange,提问作者hasan.in
相关产品推荐
相关产品推荐

