2012-06-08 135 views
6

我有一個json,其日期爲2012-06-07T00:29:47.000並且必須反序列化。 但在DataContractJsonSerializer解析iso 8601日期

DataContractJsonSerializer serializer = new DataContractJsonSerializer(type); 
return (object)serializer.ReadObject(Util.GetMemoryStreamFromString(json)); 

我得到異常下面

There was an error deserializing the object of type System.Collections.Generic.List`1 
[[MyNameSpace.MyClass, MyNameSpace, Version=1.0.4541.23433, Culture=neutral, PublicKeyToken=null]]. 
DateTime content '2012-06-07T00:29:47.000' does not start with '\/Date(' and end with ')\/' as required for JSON 

它工作在Windows Mobile 7的 但相同的代碼在Windows 8工作
據預計日期格式\/Date(1337020200000+0530)\/代替的2012-06-07T00:29:47.000

是否需要自定義序列化,如果是的話怎麼樣? 而且我不能使用JSON.NET我必然會使用DataContractJsonSerializer,我無法更改JSON的格式,因爲相同的JSON用於android。
我是.net新手。 謝謝。

回答

7

使用一個字符串屬性進行序列化/反序列化,並使用單獨的非序列化屬性將其轉換爲DateTime。更容易看到一些示例代碼:

[DataContract] 
public class LibraryBook 
{ 
    [DataMember(Name = "ReturnDate")] 
    // This can be private because it's only ever accessed by the serialiser. 
    private string FormattedReturnDate { get; set; } 

    // This attribute prevents the ReturnDate property from being serialised. 
    [IgnoreDataMember] 
    // This property is used by your code. 
    public DateTime ReturnDate 
    { 
     // Replace "o" with whichever DateTime format specifier you need. 
     // "o" gives you a round-trippable format which is ISO-8601-compatible. 
     get { return DateTime.ParseExact(FormattedReturnDate, "o", CultureInfo.InvariantCulture); } 
     set { FormattedReturnDate = value.ToString("o"); } 
    } 
} 

你可以做解析在FormattedReturnDate的制定者,而不是,允許如果接收到錯誤的日期是失敗更早。


編輯,包括GôTô的建議,應賦予序列數據成員的姓名權。

+0

什麼是'2012-06-07T00:29:47.000'的日期格式化程序我已經創建了'yyyy' - 'MM' - 'dd'T'HH':'mm':'ss', t知道如何處理'.000' –

+1

@InderKumarRathore您可以使用'f',例如'YYYY ' - ' MM ' - ' dd'T'HH ':' 毫米 ':' SS fff'。'。但'o'的[標準格式說明符](http://msdn.microsoft.com/en-us/library/az4se3k1.aspx)[已經非常接近](http://msdn.microsoft.com /en-us/library/az4se3k1.aspx#Roundtrip),但如果您的DateTime.Kind是「Utc」或「Local」,它將包含時區。 – shambulator

+0

感謝您的建議,它的工作。 :) –