序列化可观察集合时出错

本文关键字:出错 集合 观察 序列化 | 更新日期: 2023-09-27 18:33:50

我有一个可观察的集合,我正在尝试序列化到磁盘。 收到的错误是:

 Type 'VisuallySpeaking.Data.GrammarList' with data contract name
 'GrammarList:http://schemas.datacontract.org/2004/07/VisuallySpeaking.Data'
 is not expected. Consider using a DataContractResolver or add any
 types not known statically to the list of known types - for example,
 by using the KnownTypeAttribute attribute or by adding them to the
 list of known types passed to
 DataContractSerializer."}  System.Exception
 {System.Runtime.Serialization.SerializationException}

这是我的数据对象:

namespace VisuallySpeaking.Data
{
    [CollectionDataContract]
    public class GrammarList : ObservableCollection<GrammarDataObject>
{
    public GrammarList() : base()
    {
        Add(new GrammarDataObject("My Name", "My name is","Assets/SampleAssets/MyName.png"));
        Add(new GrammarDataObject("Where is", "Where is",""));
        Add(new GrammarDataObject("Dog", "I have a dog","/Assets/SampleAssets/westie.jpg"));
    }
  }
  [DataContract]
  public class GrammarDataObject :  VisuallySpeaking.Common.BindableBase
  {
      private string _Name;
      private string _SpeakingText;
      private string _ImagePath;

      public GrammarDataObject(string Name, string SpeakingText, string ImagePath)
      {
          this.Name = Name;
          this.SpeakingText = SpeakingText;
          this.ImagePath = ImagePath;
      }
      [DataMember]
      public string Name
      {
          get { return _Name; }
          set
          {
              if (this._Name != value)
              {
                  this._Name = value;
                  this.OnPropertyChanged("Name");
              }
          }
      }
      [DataMember]
      public string SpeakingText
      {
          get { return _SpeakingText; }
          set
          {
              if (this._SpeakingText != value)
              {
                  this._SpeakingText = value;
                  this.OnPropertyChanged("SpeakingText");
              }
          }
      }
      [DataMember]
      public string ImagePath
      {
          get { return _ImagePath; }
          set
          {
              if (this._ImagePath != value)
              {
                  this._ImagePath = value;
                  this.OnPropertyChanged("ImagePath");
              }
          }
      }
  }

根据Fresh的评论,我也在这里添加了BindableBase。

namespace VisuallySpeaking.Common
{
    /// <summary>
    /// Implementation of <see cref="INotifyPropertyChanged"/> to simplify models.
    /// </summary>
    [Windows.Foundation.Metadata.WebHostHidden]
    [DataContract(IsReference = true)]
    public abstract class BindableBase : INotifyPropertyChanged
    {
        /// <summary>
        /// Multicast event for property change notifications.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;
        /// <summary>
        /// Checks if a property already matches a desired value.  Sets the property and
        /// notifies listeners only when necessary.
        /// </summary>
        /// <typeparam name="T">Type of the property.</typeparam>
        /// <param name="storage">Reference to a property with both getter and setter.</param>
        /// <param name="value">Desired value for the property.</param>
        /// <param name="propertyName">Name of the property used to notify listeners.  This
        /// value is optional and can be provided automatically when invoked from compilers that
        /// support CallerMemberName.</param>
        /// <returns>True if the value was changed, false if the existing value matched the
        /// desired value.</returns>
        protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
        {
            if (object.Equals(storage, value)) return false;
            storage = value;
            this.OnPropertyChanged(propertyName);
            return true;
        }
        /// <summary>
        /// Notifies listeners that a property value has changed.
        /// </summary>
        /// <param name="propertyName">Name of the property used to notify listeners.  This
        /// value is optional and can be provided automatically when invoked from compilers
        /// that support <see cref="CallerMemberNameAttribute"/>.</param>
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var eventHandler = this.PropertyChanged;
            if (eventHandler != null)
            {
                eventHandler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

我假设我不知何故错误地标记了我的GrammarList类,但它让我无法解决。

更新:在错误消息之后(当然(,我添加了KnowTypeAttribute,它似乎有效:

[CollectionDataContract(Name = "GrammarList"),KnownType(typeof(GrammarList))]
public class GrammarList : ObservableCollection<GrammarDataObject>

同样,感谢 Fresh,我用 Name="GrammarList" 更新了 CollectionDataContract,但现在当我从磁盘重新冻结 XML 文件时出现问题。 我收到以下错误消息:

期望来自命名空间的元素"语法列表" "http://schemas.datacontract.org/2004/07/VisuallySpeaking.Data.. 遇到名称为"语法数据对象"的"元素",命名空间 "http://schemas.datacontract.org/2004/07/VisuallySpeaking.Data"。

序列化的 XML 如下所示:

<?xml version="1.0"?>    
<GrammarDataObject xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/VisuallySpeaking.Data" i:type="GrammarList">        
    <GrammarDataObject xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" z:Id="i1">    
         <ImagePath>Assets/SampleAssets/MyName.png</ImagePath>    
         <Name>My Name</Name>    
         <SpeakingText>My name is</SpeakingText>    
    </GrammarDataObject>

    <GrammarDataObject xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" z:Id="i3">    
        <ImagePath/>  
        <Name>Where is</Name>    
        <SpeakingText>Where is</SpeakingText>    
     </GrammarDataObject>

    <GrammarDataObject xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" z:Id="i4">    
        <ImagePath>/Assets/SampleAssets/westie.jpg</ImagePath>    
        <Name>Dog</Name>    
        <SpeakingText>I have a dog</SpeakingText>    
    </GrammarDataObject>    
</GrammarDataObject>

为什么 XML 外部标记未列为"语法列表"? 我认为这就是反序列化程序正在寻找的。 当我手动编辑序列化的 xml 以将 GrammarList 作为外部标记时,它会相应地反序列化。 我确信我又错过了什么!

再次更新当我序列化时,我有以下代码:

DataContractSerializer serializer = new DataContractSerializer(typeof(GrammarDataObject));

我将其更改为序列化为语法列表并修复!! 感谢您的帮助新鲜。

DataContractSerializer serializer = new DataContractSerializer(typeof(GrammarList));

序列化可观察集合时出错

查看 XML 输出,看起来集合的名称在反序列化时丢失了。

尝试在 CollectionDataContract 上设置 Name 属性,即

[CollectionDataContract(Name="GrammarList"),KnownType(typeof(GrammarList))]
public class GrammarList : ObservableCollection<GrammarDataObject>