DataContractJsonSerializer解析iso 8601日期

Ind*_*ore 8 .net c# windows-phone-7 windows-8 .net-4.5

我有一个json,它有日期2012-06-07T00:29:47.000,必须反序列化.但是

 DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);
 return (object)serializer.ReadObject(Util.GetMemoryStreamFromString(json));
Run Code Online (Sandbox Code Playgroud)

我得到以下异常

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
Run Code Online (Sandbox Code Playgroud)

它在Windows Mobile 7中工作,但相同的代码在Windows 8中不起作用.
它期待日期格式\/Date(1337020200000+0530)\/而不是2012-06-07T00:29:47.000.

它是否需要自定义序列化,如果是,那么如何?我不能使用JSON.NET我必然会使用DataContractJsonSerializer我不能改变JSON的格式,因为相同的JSON用于Android.
我是.net的新手.谢谢.

sha*_*tor 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"); }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在FormattedReturnDate的setter中进行解析,以便在收到错误日期时允许它更早失败.


编辑包括GôTô的建议,为序列化DataMember提供正确的名称.

  • @InderKumarRathore你可以使用`f`,例如'yyyy' - 'MM' - 'dd'T'HH':'mm':'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`,它将包含一个时区. (2认同)