【发布时间】:2015-08-17 22:15:04
【问题描述】:
我有一个 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;
}
}
}
【问题讨论】:
标签: c# json serialization