gpt4 book ai didi

c# - 如何使用 System.Runtime.Serialization.Json 序列化对象列表?

转载 作者:行者123 更新时间:2023-11-30 22:15:32 25 4
gpt4 key购买 nike

我试图避免使用任何第三方 DLL 将某些数据转换为 JSON。

假设我有课:

public class NodeData {

public int NodeID { get; set; }
public int ParentID { get; set; }
public int Index { get; set; }
public string FriendlyName { get; set; }

public NodeData(int nodeID, int parentID, int index, string friendlyName) {
this.NodeID = nodeID;
this.ParentID = parentID;
this.Index = index;
this.FriendlyName = friendlyName;
}
}

然后我使用 DataContractJsonSerializer 将构建的 NodeData 对象列表转换为 JSON 字符串,如下所示:

MemoryStream ms = new MemoryStream();
DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(List<NodeData>));
ds.WriteObject(ms, data);

string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();

这将引发 System.Runtime.Serialization.InvalidDataContractException:

Type 'xxx.xxx.NodeData' 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

如何使用 System.Runtime.Serialization.Json 使我的列表有效以序列化为 JSON?

最佳答案

如错误消息所述,添加 DataContract 和 DataMethod 属性。

[DataContract]  
public class NodeData {
[DataMember]
public int NodeID { get; set; }
[DataMember]
public int ParentID { get; set; }
[DataMember]
public int Index { get; set; }
[DataMember]
public string FriendlyName { get; set; }

public NodeData(int nodeID, int parentID, int index, string friendlyName) {
this.NodeID = nodeID;
this.ParentID = parentID;
this.Index = index;
this.FriendlyName = friendlyName;
}
}

这些属性帮助框架知道如何序列化对象。

关于c# - 如何使用 System.Runtime.Serialization.Json 序列化对象列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17890813/

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