I have a graph object, that I need to serialize. Nomatter which members i implement, the method returns {}
string json = new JavascriptSerializer().Serialize(routeGraph);
Here is my graph class:
namespace GraphClass
{
[Serializable, DataContract]
public class Graph : ISerializable
{
[DataMember]
readonly Dictionary<string, Node> nodeMap = new Dictionary<string, Node>();
[DataMember]
private Tuple<string, string, double> bufferOriginalOffer;
}
[Serializable, DataContract]
public class Node : ISerializable
{
[DataMember]
public string Name { get; private set; }
[DataMember]
public List<Edge> Adj { get; private set; }
[DataMember]
public Node Prev { get; set; }
[DataMember]
public double Distance { get; set; }
[Serializable, DataContract]
public class Edge : IComparable, ISerializable
{
[DataMember]
public Node Destination { get; private set; }
[DataMember]
public double Cost { get; set; }
[DataMember]
public double Time { get; set; }
}
[Serializable, DataContract]
public class Tuple<T, T1, T2> : ISerializable
{
[DataMember]
public T Item1 { get; set; }
[DataMember]
public T1 Item2 { get; set; }
[DataMember]
public T2 Item3 { get; set; }
}
}
I’ve tried for a whole day, to serialize this to either JSON or XML, as I have to send the object to a webservice.
UPDATE:
Used DataContractJsonSerialiser instead. I get the following error:
Object graph for type 'GraphClass.Edge' contains cycles and cannot be serialized if reference tracking is disabled.
As you can see in the Node class, a Node can contain a list of edges. I’m at a loss about fixing the error though.
Did you perhaps intend to use
DataContractJsonSerializer? This is more data-contract oriented;JavascriptSerializerdoesn’t really care at all about data-contracts – it just looks at the type meta.Graphonly has private fields;JavascriptSerializeronly looks at public members. Add a public property fornodeMap, perhaps?Note that
[Serializable]does nothing here, and those types don’t implementISerializableetc, despite claiming to.Edit: confirmed the following seems to work OK:
and the following seems to work after adding a property: