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

时间:2015-08-17 13:51:42

标签: c# json serialization

我有一个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;
     }   
   }
}

1 个答案:

答案 0 :(得分:3)

dcjs的声明更改为

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

因为您要序列化 myClass 列表