当复杂对象包含不可为空的DateTime成员时,如何解决SerializationException?

时间:2017-02-20 08:43:18

标签: c# wcf

我正在使用WCF将一些对象转换为JSON。 有时会出现错误:

  

SerializationException:转换为UTC时,大于DateTime.MaxValue或小于DateTime.MinValue的DateTime值无法序列化为JSON。

根据this post,我可以通过设置来解决它 类似DateTime的对象{J} dt = DateTime.SpecifyKind(dt, DateTimeKind.Utc)。当我的班级不是复合时,这很好地解决了,例如:

public class MyObj : BaseObj
{
    [XmlElement(Order = 0, ElementName = "name")]
    public string Name { get; set; }
    [XmlElement(Order = 1, ElementName = "xDate")]
    public DateTime? XDate { get; set; }
    [XmlElement(Order = 2, ElementName = "yDate")]
    public DateTime YDate { get; set; }

}

[Serializable]
public class BaseObj
{
    [XmlElement(Order = 0,ElementName = "pDate")]
    public DateTime? PDate { get; set; }
    [XmlElement(Order = 1, ElementName = "qDate")]
    public DateTime QDate { get; set; }
}

编辑:

我实际上并没有创建MyObj的实例。我传递了对象并在其周围创建了一个包装器

/*..some factory creates the instance `mo` and returns it...*/
MyObjWrapper wrapped = new MyObjWrapper() {MyObject = mo};

public class MyObjWrapper{
    [XmlIgnore]
    private MyObj _myObject;

    [XmlElement(Order = 0, ElementName = "Arg1")]
    public MyObj MyObject {
        get{ return _myobject; }
        set{
            value.GetType().GetProperties().ToList().ForEach(
                m => { if (m.PropertyType.Equals(typeof(DateTime))) m.SetValue(value, DateTime.SpecifyKind((DateTime)m.GetValue(value), DateTimeKind.Utc)); });
            _myobject = value;
        }
    }
}

当类更复杂时(如果它的成员是包含不可为空的日期时间的用户定义类),我该怎么办呢?我无法将成员设置为可空类型DateTime?。 例如:

public class MyObj : BaseObj
{
    [XmlElement(Order = 0, ElementName = "name")]
    public string Name { get; set; }
    [XmlElement(Order = 1, ElementName = "xDate")]
    public DateTime? XDate { get; set; }
    [XmlElement(Order = 2, ElementName = "yDate")]
    public DateTime YDate { get; set; }
    [XmlElement(Order = 3, ElementName = "kaBoom")]
    public AnotherObj KaBoom {get; set;} /*This contains a non-nullable DateTime member which causes the exception */
}

[Serializable]
public class AnotherObj
{
    [XmlElement(Order = 0,ElementName = "objID")]
    public int ObjID {get; set;}
    [XmlElement(Order = 1,ElementName = "anotherDate")]
    public DateTime AnotherDate {get; set;} 
}

1 个答案:

答案 0 :(得分:0)

您可以在json对象定义中使用此变通方法

[IgnoreDataMember]
public DateTime dateObject;

public string dateCustomSerialize
{
 get {
//Custom get
}
set {
//Custom set
}
}