将数据转换为JSON流时,类型无法序列化错误

本文关键字:类型 序列化 错误 流时 数据 转换 JSON | 更新日期: 2023-09-27 18:08:23

我有一个myClass类型的对象列表:

List<myClass> myList = new List<myClass>();

,我使用以下代码将其放入MemoryStream中,并注意将所有数据写入json文件:

 MemoryStream ms = new MemoryStream();
 DataContractJsonSerializer dcjs =new DataContractJsonSerializer(typeof(myClass));
            dcjs.WriteObject(ms, myList); <--ERROR HERE

上面给出了一个错误:

"Type 'System.Collections.Generic.List`1[[myClassToJSON.myClass, myClassToJSON, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' 
with data contract name 'ArrayOfmyClass:http://schemas.datacontract.org/2004/07/myClassToJSON' 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."

如果我删除[DataContract]属性形式前面的类的名称,我得到一个不同的错误:

"Type 'myClassToJSON.myClass' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you  want serialized with the DataMemberAttribute attribute.  If the type is a   collection, consider marking it with the CollectionDataContractAttribute.  See  the Microsoft .NET Framework documentation for other supported types."

我的班级在下面:

namespace myClassToJSON
{
    [DataContract]
    class myClass
    {
       private string _name { get; set; }
       private string _type { get; set; }
       private string _value { get; set; }
       private string _units { get; set; }
       public string MName
      {
        get { return _name; }
        set { _name = value; }
      }
      public string MType
     {
        get { return _type; }
        set { _type = value; }
     }
     public string MValue
     {
        get { return _value; }
        set { _value = value; }
     }
     public string MUnits
     {
        get { return _units; }
        set { _units = value; }
     }
     public myClass(string sName, string sType,string sValue, string sUnits)
    {
       _name = sName;
       _type = sType;
       _value = sValue;
       _units = sUnits;
     }   
   }
}

将数据转换为JSON流时,类型无法序列化错误

更改dcjs的声明为

DataContractJsonSerializer dcjs =new DataContractJsonSerializer(typeof(List<myClass>));

因为你正在序列化myClass

List