Json.net getter属性未序列化

编程入门 行业动态 更新时间:2024-10-28 06:24:42
本文介绍了Json getter属性未序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经开始使用json来产生更好的DateTime,但是我注意到我的属性之一没有被序列化.它没有setter,其getter依赖于对象的另一个成员,例如

I've started using json to produce better DateTimes, but I've noticed that one of my properties isn't being serialized. It has no setter, and its getter is reliant upon another member of the object, e.g.

public int AmountInPence { get; set;} public decimal AmountInPounds { get { return (decimal)AmountInPence / 100; } }

我做了一个继承自JsonResult的类,主线是:

I've made a class that inherits from JsonResult and the main line is:

string serializedObject = JsonConvert.SerializeObject(Data, new IsoDateTimeConverter());

有人可以告诉我如何强制它序列化该属性吗?

Can anyone tell me how to force it to serialize that property?

只是为了澄清-这是一个简化的示例.我已经对其进行了更新,以反映出我首先将int强制转换为十进制.我以前忘记检查了,但是该属性是部分类的一部分,因为它是从WCF服务返回的.我在我的程序集中声明了该属性,所以这可能是一个线索吗?

Just to clarify - that was a simplified example. I've updated it to reflect that I am casting the int to decimal first. I'd forgotten to check previously, but the property is part of a partial class, because it's being returned from a WCF service. I'm declaring that property in my assembly, so could this be a clue?

推荐答案

Json没有任何问题.它可以序列化只读属性就好了. 问题出在您的AmountInPounds

There is nothing wrong with the Json. It can serialize read only properties just fine. The problem is in your AmountInPounds

public decimal AmountInPounds { get { return AmountInPence / 100; } }

因为您正在使用/ 100进行整数除法,这意味着如果AmountInPence小于100,您将得到0.

Because your are doing integer division with / 100 it means you will get 0 if AmountInPence is less than 100.

您需要使用 m后缀以将100标记为decimal:

What you need is to use the m suffix to mark 100 as decimal:

public decimal AmountInPounds { get { return AmountInPence / 100m; } }

在AmountInPounds中获得正确的结果.

评论后

计算出的属性AmountInPounds是WCF服务生成的DataContract的部分类 .

The calculated property AmountInPounds was in a partial class of a WCF service's generated DataContract.

在DataContract中,如果未用DataMemberAttribute标记属性,则似乎不会对其进行序列化.

And in DataContract if a property is not marked with DataMemberAttribute it seems it won't be serialized.

因此,在OP的答案旁边:

So beside the OP's answer:

[JsonPropertyAttribute(DefaultValueHandling = DefaultValueHandling.Include)] public decimal AmountInPounds { get { return (decimal)AmountInPence / 100; } }

这也有效:

[System.Runtime.Serialization.DataMemberAttribute()] public decimal AmountInPounds { get { return (decimal)AmountInPence / 100; } }

更多推荐

Json.net getter属性未序列化

本文发布于:2023-11-14 21:30:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1588548.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   序列化   Json   net   getter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!