I have a WCF service to which I am adding new endpoints that use idiomatic HTTP+JSON. I bumped into the DateTime formatting issue, and tried to fix it like this:
[DataContract]
public class PingResponse
{
[IgnoreDataMember] public DateTime SystemDateTimeLocal;
[IgnoreDataMember] public DateTime SystemDateTimeUTC;
[DataMember] public string Version;
[DataMember(EmitDefaultValue = false, Name = nameof(SystemDateTimeLocal)), EditorBrowsable(EditorBrowsableState.Never)]
public string SystemDateTimeLocalFormatted
{
get => SystemDateTimeLocal.ToString(Constants.DateTimeFormat);
set => SystemDateTimeLocal = DateTime.ParseExact(value, Constants.DateTimeFormat, CultureInfo.InvariantCulture);
}
[DataMember(EmitDefaultValue = false, Name = nameof(SystemDateTimeUTC)), EditorBrowsable(EditorBrowsableState.Never)]
public string SystemDateTimeUTCFormatted
{
get => SystemDateTimeUTC.ToString(Constants.DateTimeFormat);
set => SystemDateTimeUTC = DateTime.ParseExact(value, Constants.DateTimeFormat, CultureInfo.InvariantCulture);
}
}
But, the resulting object is serialized with SystemDateTimeLocalFormatted
and SystemDateTimeUTCFormatted
properties, ignoring the Name
on the DataMember
attributes. Is there a way to achieve what I want that doesn't involve swapping out the serialization stack? :-P
Update: I just copied this type into a test app and explicitly used DataContractJsonSerializer
and it did not ignore the Name
field -- so I am forced to conclude that the original project is archieving its JSON serialization with a different serializer. I haven't yet looked into identifying which one.
I have found the cause. It's a weird one. I found a dummy DataContractAttribute.cs
in our project. This was silently taking the place of the real DataContractAttribute
, so that DataContractJsonSerializer
didn't detect the type having a data contract. Removing the DataContractAttribute.cs
from the project so that the source code instead uses the real System.Runtime.Serialization.DataContractAttribute
has resolved the problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.