Daniel
Daniel

Reputation: 11054

How do I serialize a list of objects with System.Runtime.Serialization.Json?

I'm trying to avoid using any third party DLLs to turn some data to JSON.

Say I have the class:

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

Then I use the DataContractJsonSerializer to turn a constructed list of NodeData objects to a JSON string like so:

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

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

This throws a 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

How would I make my list valid for serialization to JSON with System.Runtime.Serialization.Json?

Upvotes: 2

Views: 1813

Answers (1)

AntLaC
AntLaC

Reputation: 1225

As the error message states, add the DataContract and DataMethod attributes.

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

These attributes are what help the framework know how to serialize the objects.

Upvotes: 3

Related Questions