Json.net getter property not serialized

眉间皱痕 提交于 2019-12-07 03:23:55

问题


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?


回答1:


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



回答2:


OK looks like I've found the answer, sorry for not providing more details in the post, but I don't think it mattered in the end.

I needed to add an attribute on the AmountInPounds property:

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


来源:https://stackoverflow.com/questions/9727836/json-net-getter-property-not-serialized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!