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
AmountInPoundsBecause your are doing integer division with
/ 100it means you will get0ifAmountInPenceis less than 100.What you need is to use the m suffix to mark 100 as
decimal:to get the right result in
AmountInPounds.EDIT after comments:
The calculated property
AmountInPoundswas in a partial class of a WCF service’s generatedDataContract.And in
DataContractif a property is not marked withDataMemberAttributeit seems it won’t be serialized.So beside the OP’s answer:
This is also works: