DataContractSerialization适用于一个对象,对于类似的对象则失败

时间:2015-04-16 15:29:50

标签: datacontractserializer datacontract

我成功序列化了以下类

[DataContract]
public class Event
{           
    [DataMember] public virtual string EventId { get; set; }        
    [DataMember] public virtual string Name { get; set; }        
    [DataMember] public virtual string Editable { get; set; }        
    [DataMember] public virtual DateTime? CreatedOn { get; set; }            
    [DataMember] public virtual Function Function { get; set; }        
    [DataMember] public virtual User CreatedBy { get; set; }
    [DataMember] public virtual IList<EventParameter> Parameters { get; set; }
    [DataMember] public virtual IList<EventParameterOption> Options { get; set; }

    public Event()
    {
        Parameters = new List<EventParameter>();
        Options = new List<EventParameterOption>();
    }
}

但序列化以下

时,相同的代码会产生异常
[DataContract]
public class Attribute
{
    [DataMember] public virtual string AttributeId { get; set; }
    [DataMember] public virtual string Name { get; set; }
    [DataMember] public virtual string Description { get; set; }
    [DataMember] public virtual string Status { get; set; }
    [DataMember] public virtual Function Function { get; set; }
    [DataMember] public virtual Category Category { get; set; }
    [DataMember] public virtual string Editable { get; set; }
    [DataMember] public virtual string Column { get; set; }
    [DataMember] public virtual DateTime? LastExecution { get; set; }
    [DataMember] public virtual DateTime? LastUpdate { get; set; }
    [DataMember] public virtual DateTime? CreatedOn { get; set; }
    [DataMember] public virtual User CreatedBy { get; set; }
    [DataMember] public virtual IList<AttributeParameter> Parameters { get; set; }

    public Attribute()
    {
        Parameters = new List<AttributeParameter>();
    }
}

,异常指向Attribute类的User属性。

不希望输入数据合约名称为“UserProxy:http://schemas.datacontract.org/2004/07/”的“UserProxy”。考虑使用DataContractResolver或将任何静态未知的类型添加到已知类型列表中 - 例如,使用KnownTypeAttribute属性或将它们添加到传递给DataContractSerializer的已知类型列表中。

我用于序列化的代码是

public static byte[] SerializeObjectDataContract(object obj)
    {
        using (var stream = new MemoryStream())            
        {
            var serializer = new DataContractSerializer(obj.GetType());
            serializer.WriteObject(stream, obj);
            stream.Position = 0;
            return stream.ToArray();
        }
    }

我真的不明白两个序列号之间的区别。从User属性中删除DataMember属性允许序列化完成,但我也需要序列化用户。

0 个答案:

没有答案