【问题标题】:DataContractJsonSerializer serialization error: Consider using a DataContractResolver or add any types not known statically to the listDataContractJsonSerializer 序列化错误:考虑使用 DataContractResolver 或将任何静态未知的类型添加到列表中
【发布时间】:2014-06-27 09:14:08
【问题描述】:

我正在扩展使用System.Runtime.Serialization.Json.DataContractJsonSerializer 序列化的对象,并具有两个通过继承作为字符串(不是复杂类型)的附加属性。使用的 .Net 版本是 .NET 4。
序列化机制适用于基础对象,但对于具有两个附加属性的对象却失败了,这对我来说似乎很奇怪。
我在基础对象和继承对象上都使用[DataContract] 属性,并且它们的所有属性都具有[DataMember] 属性和名称。
这两个对象都是内部的,但我看不出这会如何影响子对象的序列化。
在调试时,我观察到基础对象进入try 块并被序列化,并且子对象在serializer.WriteObject(ms, sourceObject);
在继承的对象上添加已知类型属性 [KnownType(typeof(OnTheMoveBusinessComponentJavaScriptInitObject))] 会导致在同一位置出现相同的错误。
为什么不能用继承的对象替换基础对象?

子对象:

namespace OnTheMoveLibrary.DataControls
{
    [DataContract]
    [KnownType(typeof(OnTheMoveBusinessComponentJavaScriptInitObject))]
    internal class OnTheMoveTreeBusinessComponentJavaScriptInitObject : OnTheMoveBusinessComponentJavaScriptInitObject
    {
        [DataMember(Name = "MasterRecordId")]
        public string MasterRecordId { get; set; }

        [DataMember(Name = "ParentRecordId")]
        public string ParentRecordId { get; set; }
    }
}

基础对象:

namespace OnTheMoveLibrary.DataControls
{
    [DataContract]
    internal class OnTheMoveBusinessComponentJavaScriptInitObject : OnTheMoveValidatable
    {
        public OnTheMoveBusinessComponentJavaScriptInitObject()
        {
            this.SqlStatementObject = new OnTheMoveSelectStatement();
            this.PreDefaults = new PreDefaultsObject();
            this.ParentAssociations = new List<ParentAssociation>();
            this.CalculatedFields = new List<OnTheMoveCalculatedField>();
            this.BusinessComponentEvents = new List<BusinessComponentEvent>();
        }

        [DataMember(Name = "sqlStatementObject")]
        public IOnTheMoveSelectStatement SqlStatementObject { get; set; }

        [DataMember(Name = "calculatedFields")]
        public List<OnTheMoveCalculatedField> CalculatedFields { get; set; }

        [DataMember(Name = "knockoutContextName")]
        public string KnockoutContextName { get; set; }

        [DataMember(Name = "observable")]
        public bool Observable { get; set; }

        [DataMember(Name = "integrationObjectNameForNewRecords")]
        public string IntegrationObjectNameForNewRecords { get; set; }

        [DataMember(Name = "singleRecordNewFlag")]
        public bool SingleRecordNewFlag { get; set; }

        [DataMember(Name = "recordIndex")]
        public int? RecordIndex { get; set; }

        [DataMember(Name = "primaryTableName")]
        public string PrimaryTableName { get; set; }

        /// <summary>
        /// The index within the query string of the "RecordId" parameter to use as a parent to insert new records, defaulting to 0
        /// For example, if we have a recordid of "A123,B123" in the querystring, and set ParentQSRecordIdIndex=1, then B123 is used as the parent object when saving
        /// </summary>
        [DataMember(Name = "parentRecordIdQueryStringIndex")]
        public int? ParentRecordIdQueryStringIndex { get; set; }

        [DataMember(Name = "parentAssociations")]
        public List<ParentAssociation> ParentAssociations { get; set; }

        [DataMember(Name = "applyBindings")]
        public bool ApplyBindings { get; set; }

        [DataMember(Name = "PreDefaults")]
        public PreDefaultsObject PreDefaults { get; set; }

        /// <summary>
        /// Gets or sets a list of <see cref="BusinessComponentEvent">BusinessComponentEvents</see>.
        /// </summary>
        [DataMember(Name = "businessComponentEvents")]
        public List<BusinessComponentEvent> BusinessComponentEvents { get; set; }

        [DataMember(Name = "automaticLeadingWildcards")]
        public bool? AutomaticLeadingWildcards { get; set; }

        [DataMember(Name = "automaticTrailingWildcards")]
        public bool? AutomaticTrailingWildcards { get; set; }

        [DataMember(Name = "enableAggregateFields")]
        public bool? EnableAggregateFields { get; set; }

        public override void ValidateProperties()
        {
            this.ValidateProperty("SqlStatementObject", this.SqlStatementObject != null ? this.SqlStatementObject.ToString() : null);
            this.SqlStatementObject.ValidateProperties();
        }
    }
}

序列化机制:

public static string ObjectToJson<TValue>(TValue sourceObject)
    {
        string result = null;
        Type type = typeof(TValue);

        if (type == typeof(object))
        {
            return CallObjectToJsonWithSpecificType(sourceObject);
        }

        Type[] knownTypes = new[] { typeof(OnTheMoveSelectStatement), typeof(OnTheMoveCustomSelectStatement) };
        var serializer = new DataContractJsonSerializer(type, knownTypes);
        var ms = new MemoryStream();
        try
        {
            serializer.WriteObject(ms, sourceObject);
            result = Encoding.UTF8.GetString(ms.ToArray());
        }
        finally
        {
            ms.Close();
        }

        return result;
    }

【问题讨论】:

    标签: c# json serialization .net-4.0 datacontractserializer


    【解决方案1】:

    我自己想出来的。

    而不是在继承的类中添加基类类型的属性

    [DataContract]
    [KnownType(typeof(OnTheMoveBusinessComponentJavaScriptInitObject))]
    internal class OnTheMoveTreeBusinessComponentJavaScriptInitObject : OnTheMoveBusinessComponentJavaScriptInitObject
    

    必须做相反的事情 - 使用子类类型添加到基类属性(这破坏了所有面向对象的设计,因为基类永远不应该知道谁从它继承)。

    [DataContract]
    [KnownType(typeof(OnTheMoveTreeBusinessComponentJavaScriptInitObject))]
    internal class OnTheMoveBusinessComponentJavaScriptInitObject : OnTheMoveValidatable
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-20
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      • 2012-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多