我正在尝试以无法由.NET的DateTime结构直接解析的格式读取包含日期/时间的JSON对象。为了避免在我的结构中有一个'int'字段的日期/时间,我写了一个自定义DateTimeConverter:
public class DateTimeConverter : JavaScriptConverter {
public override IEnumerable<Type> SupportedTypes {
get { return new Type[] { typeof(DateTime), typeof(DateTime?) }; }
}
public override IDictionary<string, object> Serialize(
object obj, JavaScriptSerializer serializer
) { throw new NotImplementedException(); }
public override object Deserialize(
IDictionary<string, object> dictionary, Type type,
JavaScriptSerializer serializer
) {
return DateTime.Now;
}
}
但是当我用JavaScriptSerializer读取JSON字符串时,它不使用我的自定义转换器:
public struct TextAndDate {
public string Text;
public DateTime Date;
}
static void Main() {
string json =
"{" +
" \"text\": \"hello\", " +
" \"date\": \"1276692024\"" +
"}";
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new [] { new DateTimeConverter() });
var test = serializer.Deserialize<TextAndDate>(json);
}
直接反序列化DateTime值时使用转换器 ,而不是在反序列化包含DateTime值的类型时。
为什么呢? 没有编写自定义DateTime类型或使用int?
的任何方法答案 0 :(得分:0)
您应该在DateTimeConverter
班级进行细微更改:
public class DateTimeConverter : JavaScriptConverter {
public override IEnumerable<Type> SupportedTypes {
get { return new Type[] { typeof (TextAndDate) }; }
}
public override IDictionary<string, object> Serialize (
object obj, JavaScriptSerializer serializer
) { throw new NotImplementedException (); }
public override object Deserialize (
IDictionary<string, object> dictionary, Type type,
JavaScriptSerializer serializer
) {
if (type == typeof (TextAndDate)) {
TextAndDate td = new TextAndDate ();
if (dictionary.ContainsKey ("text"))
td.Text = serializer.ConvertToType<string> (
dictionary["text"]);
//if (dictionary.ContainsKey ("date"))
td.Date = DateTime.Now;
return td;
}
else
return null;
}
}
根据评论更新:在我看来,您应该使用Message Inspectors技术(请参阅http://msdn.microsoft.com/en-us/library/aa717047.aspx)。请查看How to ignore timezone of DateTime in .NET WCF client?以获取示例。