I have a legacy application that used binary serialisation to persist the data. Now we wanted to use Json.net 4.5 to serialise the data without much changes to the existing
I think you'll need both ReferenceLoopHandling.Serialize
and PreserveReferencesHandling.All
to replicate the behavior of binary serialization. The resulting JSON may not be nearly as pretty, though.
EDIT: I've looked deeper into JSON.Net 4.5r10 and discovered a deficiency: JsonSerializerInternalWriter
doesn't check #ShouldWriteReference
for references obtained via ISerializable
.
With the foreach
loop in #SerializeISerializable
rewritten as below, your object graph round-trips successfully.
foreach (SerializationEntry serializationEntry in serializationInfo)
{
writer.WritePropertyName(serializationEntry.Name);
var entryValue = serializationEntry.Value;
var valueContract = GetContractSafe(entryValue);
if (ShouldWriteReference(entryValue, null, valueContract, null, member))
{
WriteReference(writer, entryValue);
}
else
{
SerializeValue(writer, entryValue, valueContract, null, null, member);
}
}
Did you try this?
[Serializable]
class Employee : ISerializable
{
[NonSerialized]
[XmlIgnore]
public Department Department { get; set; }
NonSerialized Indicates that a field of a serializable class should not be serialized.
XmlIgnore Instructs the Serialize method of the XmlSerializer not to serialize the public field or public read/write property value