具有自定义Get的DataMember属性?

时间:2015-04-11 19:05:42

标签: c# json rest properties datacontract

I'm going by this tutorial并尝试弄清楚如何在没有自动属性的情况下拥有DataMember。基本上我有一个字段是一个epoch格式的日期时间,我希望该属性是一个DateTime所以我试图在属性的转换中进行转换。我不确定如何准确格式化。

由于要求代码,请查看以下内容。 :

// The date looks like this in the JSON 
"someEpochDateTime": 1428785212000,

// I thought I could work around it using the following code, however
// I get a warning saying someEpochDateTime is never set.

[DataMember(Name = "someEpochDateTime")]
private long someEpochDateTime;

public DateTime test
{
get { return DateTimeConverter.FromUnixTime(someEpochDateTime); }
}

使用FromUnixTime

2 个答案:

答案 0 :(得分:0)

像这样你可以创建datereturn属性,这将返回日期

     [DataContract]
     public class Mycontractclass
     {     
         // Apply the DataMemberAttribute to the property.
        [DataMember]
        public DateTime datereturn
        {
           get
           {
              return this.dateCreated.HasValue
                 ? this.dateCreated.Value
                 : DateTime.Now;
           }

           set { this.dateCreated = value; }
        }

        private DateTime? dateCreated = null;
    }

答案 1 :(得分:0)

显然我的上一次编辑实际上是一个解决方案,我只是出于某种原因得到编译器警告。

[DataMember(Name = "someEpochDateTime")]
private long someEpochDateTime;

public DateTime test
{
    get { return DateTimeConverter.FromUnixTime(someEpochDateTime); }
}