Json.net getter property not serialized

I started using json.net to create improved DateTimes, but I noticed that one of my properties is not serializable. It does not have a setter, and its getter depends on another member of the object, for example.

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

I created a class that inherits from JsonResult, and the main line:

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

Can someone tell me how to get it to serialize this property?

Edit: Just to clarify - this was a simplified example. I updated it to reflect that I am typing int to a decimal number. I forgot to check before, but the property is part of a partial class because it is being returned from the WCF service. I declare this property in my assembly, so can this be the key?

+5
source share
3

Json.net . . AmountInPounds

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

/ 100, , 0, AmountInPence 100.

m suffix 100 decimal:

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; } }
+15

. LINQPad :

void Main()
{
    JsonConvert.SerializeObject(new A(), new IsoDateTimeConverter()).Dump();
}

public class A
{
    public int AmountInPence { get; set;}
    public decimal AmountInPounds { get { return AmountInPence / 100;  } }
}

:

{ "AmountInPence": 0, "AmountInPounds": 0,0}

+2

OK it looks like I found an answer, sorry for not adding details to the message, but I don't think it mattered at the end.

I needed to add the AmountInPounds property attribute:

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

All Articles