我有一个日期为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的新手。
感谢。
答案 0 :(得分:8)
使用一个字符串属性进行序列化/反序列化,以及一个单独的非序列化属性,将其转换为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提供正确的名称。
答案 1 :(得分:0)
在DataContractJsonSerializer构造函数中传递格式
var serializer = new DataContractJsonSerializer(
typeof(Client),
new DataContractJsonSerializerSettings {
DateTimeFormat = new DateTimeFormat("yyyy-MM-dd hh:mm:ss"),
});