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的新手.谢谢.
使用一个字符串属性进行序列化/反序列化,使用一个单独的非序列化属性将其转换为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提供正确的名称.