c# – Json.net getter属性未序列化
发布时间:2020-12-15 18:32:35 所属栏目:百科 来源:网络整理
导读:我已经开始使用json.net来生成更好的DateTimes,但我注意到我的一个属性没有被序列化.它没有setter,它的getter依赖于对象的另一个成员,例如 public int AmountInPence { get; set;}public decimal AmountInPounds { get { return (decimal)AmountInPence / 10
我已经开始使用json.net来生成更好的DateTimes,但我注意到我的一个属性没有被序列化.它没有setter,它的getter依赖于对象的另一个成员,例如
public int AmountInPence { get; set;} public decimal AmountInPounds { get { return (decimal)AmountInPence / 100; } } 我创建了一个继承自JsonResult的类,主线是: string serializedObject = JsonConvert.SerializeObject(Data,new IsoDateTimeConverter()); 谁能告诉我如何强制它序列化该属性? 编辑: 解决方法
Json.net没有任何问题.它可以很好地序列化只读属性.
问题出在AmountInPounds中 public decimal AmountInPounds { get { return AmountInPence / 100; } } 因为你正在使用/ 100进行整数除法,这意味着如果AmountInPence小于100,你将获得0. 你需要的是使用m suffix将100标记为十进制: public decimal AmountInPounds { get { return AmountInPence / 100m; } } 在AmountInPounds中获得正确的结果. 评论后编辑: 计算的属性AmountInPounds位于WCF服务生成的DataContract的部分类中. 在DataContract中,如果属性未标记为DataMemberAttribute,则它似乎不会被序列化. 除了OP的答案之外: [JsonPropertyAttribute(DefaultValueHandling = DefaultValueHandling.Include)] public decimal AmountInPounds { get { return (decimal)AmountInPence / 100; } } 这也有效: [System.Runtime.Serialization.DataMemberAttribute()] public decimal AmountInPounds { get { return (decimal)AmountInPence / 100; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |