我有一个日期为 2012-06-07T00:29:47.000
的 json,必须反序列化。
但是在
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 的新手。
谢谢。
最佳答案
使用一个字符串属性进行序列化/反序列化,并使用一个单独的非序列化属性将其转换为 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 的 setter 中进行解析,以允许它在收到错误日期时提前失败。
编辑以包含 GôTô 为序列化 DataMember 赋予正确名称的建议。
关于c# - DataContractJsonSerializer 解析iso 8601日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10945825/