gpt4 book ai didi

c# - 将数据转换为 JSON 流时出现 Type cannot be serialized 错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:31:30 24 4
gpt4 key购买 nike

我有一个 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."

我的类(class)如下:

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;
}
}
}

最佳答案

dcjs 的声明更改为

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

因为您正在序列化 myClassList

关于c# - 将数据转换为 JSON 流时出现 Type cannot be serialized 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32052192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com