Problem description
Like the next entity class, which contains a non-empty time type attribute, the default is the minimum time for C #, and when you use DataContractJsonSerializer to serialize the class object to JSON, Throw exception message: System.Runtime.Serialization.SerializationException: "When converting to UTC, greater than datetime.maxvalue or less than datetime.minvalue DateTime values cannot be serialized as JSON. ”。
Entity class
public class Post{ public string Id { get; set; } public string Title { get; set; } public string Content { get; set; } public DateTime CreateTime { get; set; }}
Serialization classes
public class DataContractProvider{ public string Serialize<T>(T value) { var serializer = GetJsonSerializer<T>(); using (var stream = new MemoryStream()) { serializer.WriteObject(stream, value); return Encoding.Default.GetString(stream.ToArray()); } } public T Deserialize<T>(string json) { var serializer = GetJsonSerializer<T>(); var bytes = Encoding.Default.GetBytes(json); using (var stream = new MemoryStream(bytes)) { return (T)serializer.ReadObject(stream); } } private DataContractJsonSerializer GetJsonSerializer<T>() { return new DataContractJsonSerializer(typeof(T)); }}
Solutions
Here are a few ways to try it:
1. To change datetime to a nullable type DateTime, you can serialize successfully, but in fact the time type of the property is non-null and therefore cannot be resolved.
2. When constructing DataContractJsonSerializer, add serialization settings Datacontractjsonserializersettings and set the time format to serialize successfully. Settings are as follows:
private DataContractJsonSerializer GetJsonSerializer<T>(){ var settings = new DataContractJsonSerializerSettings { DateTimeFormat = new DateTimeFormat("yyyy-MM-dd HH:mm:ss") }; return new DataContractJsonSerializer(typeof(T), settings);}
DataContractJsonSerializer converting to UTC overflow problem when serializing time types