序列化Observable Collection时出错

时间:2013-10-02 20:52:26

标签: c# wcf windows-store-apps observablecollection datacontractserializer

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

 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文件时出现了问题。我收到以下错误消息:

  

期望来自命名空间的元素'GrammarList'   'http://schemas.datacontract.org/2004/07/VisuallySpeaking.Data' ..   遇到'Element',名称为'GrammarDataObject',名称空间   '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外部标记未列为“GrammarList”?我认为这就是解串器正在寻找的东西。当我手动编辑序列化的xml以将GrammarList作为外部标记放置时,它会适当地反序列化。我确信我再次错过了一些东西!

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

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

我把它改为序列化为GrammarList和presto,修复!!!感谢新鲜的帮助。

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

1 个答案:

答案 0 :(得分:1)

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

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

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