I am trying to serialize / deserialize a complex type. I want to keep references to objects, which means that if an instance of an object is referenced several times in the object graph, during deserialization, I want the deserializer to only create this instance once and reference it several times (against creating an instance of the object several times )
The second thing I need a system in is a dictionary in which the key is a complex type.
I was able to achieve both with serialization of DataContractSerializer in XML. However, I cannot find a Json serializer that can do this. I tried Json.NET and ServiceStack but no luck.
See the sample code below:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using Newtonsoft.Json;
namespace Serialization
{
class Program
{
static void Main(string[] args)
{
var transportModel = CreateSampleModel();
var serializer = new DataContractSerializer(typeof(TransportModel), null, int.MaxValue, false, true, null, null);
string serializedObjectXml;
using (var sw = new StringWriter())
{
using (var writer = new XmlTextWriter(sw))
{
serializer.WriteObject(writer, transportModel);
writer.Flush();
serializedObjectXml = sw.ToString();
}
}
byte[] byteArray = Encoding.ASCII.GetBytes(serializedObjectXml);
var stream = new MemoryStream(byteArray);
var deserializedObjectXml = serializer.ReadObject(stream);
var serializedObjectJson=JsonConvert.SerializeObject(transportModel);
var deserializedObjectJson = JsonConvert.DeserializeObject(serializedObjectJson);
}
static TransportModel CreateSampleModel()
{
var transportModel = new TransportModel();
var fra = new Destination
{
Id = 0,
Name = "FRA",
Demand = 900
};
var det = new Destination
{
Id = 1,
Name = "DET",
Demand = 1200
};
var dests = new List<Destination> { fra, det};
var gary = new Origin
{
Id = 0,
Name = "GARY",
Supply = 1400,
Cost = new Dictionary<Destination, int>{
{fra, 39},
{det, 14}
}
};
var origs = new List<Origin> { gary};
transportModel.Destinations = dests;
transportModel.Origins = origs;
return transportModel;
}
}
[DataContract]
class Destination
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public int Demand { get; set; }
}
[DataContract]
class Origin
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public int Supply { get; set; }
[DataMember]
public Dictionary<Destination, int> Cost { get; set; }
}
[DataContract]
class TransportModel
{
[DataMember]
public List<Origin> Origins;
[DataMember]
public List<Destination> Destinations;
public TransportModel()
{
Origins = new List<Origin>();
Destinations = new List<Destination>();
}
}
}