2012-02-22 58 views
5

我有一個工作的WCF服務,它使用JSON作爲它的RequestFormat和ResponseFormat。WCF DataMember DateTime序列化格式

[ServiceContract]  
public interface IServiceJSON 
{ 

    [OperationContract] 
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] 
    MyClassA echo(MyClassA oMyObject); 

} 

[DataContract] 
public class MyClassA 
{ 
    [DataMember] 
    public string message; 

    [DataMember] 
    public List<MyClassB> myList; 

    public MyClassA() 
    { 
     myList = new List<MyClassB>(); 
    } 
} 

[DataContract] 
public class MyClassB 
{ 
    [DataMember] 
    public int myInt; 

    [DataMember] 
    public double myDouble; 

    [DataMember] 
    public bool myBool; 

    [DataMember] 
    public DateTime myDateTime; 

} 

MyClassB類的myDateTime屬性的類型爲DateTime。這將被序列化爲以下格式:「myDateTime」:「/ Date(1329919837509 + 0100)/」

我需要與之通信的客戶端無法處理此格式。它要求它是一個更傳統的格式,例如:yyyy-MM-dd hh:mm:ss

是否有可能將此添加到DataMember屬性?像這樣:

[DataMember format = 「yyyy-MM-dd hh:mm:ss」] 
public DateTime myDateTime; 

在此先感謝!

+0

您是否找到解決方案?我做的唯一方法是kludge解決方法,http://stackoverflow.com/questions/25894068/change-the-json-datetime-serialization-in-wcf-4-0-rest-service – bpeikes 2014-09-17 15:01:04

+0

沒有真正的解決方案,除了這個解決方法是由下面的tadagaghe描述的,它與您所指的相同:添加一個字符串類型的附加數據庫。也許你應該編輯tad的答案,並添加你的例子的完整性。 – Brabbeldas 2014-09-17 19:03:58

+0

是啊,我已經看過MS參考代碼WCF和序列化,它是不可讀的。難怪看起來他們已經通過WCF拋棄了REST。 – bpeikes 2014-09-17 19:06:50

回答

2

爲什麼不把它作爲已經格式化的字符串傳遞?

也就是說,不要將DataContract中的日期作爲日期。讓該成員變成一個字符串,然後按照客戶需要的方式格式化字符串。

+0

你能解釋一下你的意思嗎? – Brabbeldas 2012-02-24 08:11:07

+0

稍微更新了我的答案。 – 2012-02-24 15:00:36

5

下面是已經檢查答案的例子...

[DataContract] 
public class ProductExport 
{ 
    [DataMember] 
    public Guid ExportID { get; set; } 

    [DataMember(EmitDefaultValue = false, Name = "updateStartDate")] 
    public string UpdateStartDateStr 
    { 
     get 
     { 
      if(this.UpdateStartDate.HasValue) 
       return this.UpdateStartDate.Value.ToUniversalTime().ToString("s", CultureInfo.InvariantCulture); 
      else 
       return null; 
     } 
     set 
     { 
      // should implement this... 
     } 
    } 

    // this property is not transformed to JSon. Basically hidden 
    public DateTime? UpdateStartDate { get; set; } 

    [DataMember] 
    public ExportStatus Status { get; set; } 
} 

上面的類定義了兩種方法來處理UpdateStartDate。一個包含可空的DateTime屬性,另一個轉換DateTime?到我的服務的JSon響應字符串。