我試圖避免使用任何第三方DLL將一些數據轉換爲JSON。如何使用System.Runtime.Serialization.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
:
類型 'xxx.xxx.NodeData' 不能被序列化。考慮與DataContractAttribute屬性標記它 和標記所有你想要的序列化與DataMemberAttribute屬性及其 成員。 如果類型是集合,請考慮使用CollectionDataDataContractAttribute將其標記爲 。看到其他支持的類型
Microsoft .NET Framework的 文檔我將如何讓我的名單有效期爲序列化JSON與System.Runtime.Serialization.Json?