使用JsonSerializer Populate映射对象失败,仅返回默认值求助
问题原因及解决方案
核心问题:JSON结构与目标对象不匹配
你的JSON数据外层是一个包含Notification属性的根对象,但你直接用整个JObject的Reader执行Populate,序列化器会尝试将根对象的属性(仅一个Notification)映射到Notification类的属性,自然找不到匹配项,导致所有属性保留默认值。
解决方案
1. 正确定位JSON中的目标对象
调用Populate前,先从JObject中取出Notification对应的子对象,再用它的Reader填充目标实例:
JObject jo = JObject.Parse(json); // 取出内层的Notification对象 var notificationJson = jo["Notification"]; var target = new Notification(); serializer.Populate(notificationJson.CreateReader(), target);
2. 修复只读属性的赋值问题
你的DisplayName和Value属性只有get方法,没有set方法,即使JSON中有对应值,序列化器也无法为它们赋值。如果需要让这两个属性能被JSON数据覆盖,需添加set访问器:
public string DisplayName { get { return displayname; } set { displayname = value; } } public int Value { get { return _value; } set { _value = value; } }
若不需要从JSON赋值,保持现有只读逻辑即可,但这两个属性会始终返回硬编码的默认值。
验证后的完整代码示例
string json = @" { ""Notification"": { ""Id"": 4, ""CreatedById"": 1, ""CreatedBy"": null, ""CreatedDateTime"": ""2023-05-31T21:44:44.9659592+01:00"", ""PushMessage"": ""Notify me now"", ""ScheduledDateTime"": ""2023-05-31T22:46:00+01:00"", ""Reach"": 1, ""OrganizationId"": 1, ""Organization"": { ""Id"": 1, ""Name"": ""orgname"" }, ""UserNotifications"": [], ""Value"": 1, ""DisplayName"": ""OrgNotification"" } }"; JObject jo = JObject.Parse(json); var notificationJson = jo["Notification"]; var target = new Notification(); var serializer = new JsonSerializer(); // 确保serializer已正确初始化 serializer.Populate(notificationJson.CreateReader(), target); public class Notification { private string displayname; private int _value; public int Id { get; set; } public int CreatedById { get; set; } public User CreatedBy { get; set; } public DateTimeOffset CreatedDateTime { get; set; } public string PushMessage { get; set; } public DateTimeOffset? ScheduledDateTime { get; set; } public int Reach { get; set; } public int OrganizationId { get; set; } public Organization Organization { get; set; } public string DisplayName { get; set; } public int Value { get; set; } } public class Organization { public int Id { get; set; } public string Name { get; set; } } // 补充User类定义(原代码未给出,否则序列化时会报错) public class User { }
内容的提问来源于stack exchange,提问作者Little Geeza
相关产品推荐
相关产品推荐

