Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.net getter property not serialized

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?

like image 463
NickL Avatar asked Mar 15 '12 20:03

NickL


1 Answers

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; } }
like image 54
nemesv Avatar answered Sep 28 '22 02:09

nemesv