I've started using json.net 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; } }
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?
Edit: 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?
There is nothing wrong with the Json.net. It can serialize read only properties just fine.
The problem is in your AmountInPounds
public decimal AmountInPounds { get { return AmountInPence / 100; } }
Because your are doing integer division with / 100
it means you will get 0
if AmountInPence
is less than 100.
What you need is to use the m suffix to mark 100 as decimal
:
public decimal AmountInPounds { get { return AmountInPence / 100m; } }
to get the right result in AmountInPounds
.
EDIT after comments:
The calculated property AmountInPounds
was in a partial class of a WCF service's generated DataContract
.
And in DataContract
if a property is not marked with DataMemberAttribute
it seems it won't be serialized.
So beside the OP's answer:
[JsonPropertyAttribute(DefaultValueHandling = DefaultValueHandling.Include)]
public decimal AmountInPounds { get { return (decimal)AmountInPence / 100; } }
This is also works:
[System.Runtime.Serialization.DataMemberAttribute()]
public decimal AmountInPounds { get { return (decimal)AmountInPence / 100; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With