Reputation: 2480
It's easier to show a mock up of the problem rather than trying to explain it first.
internal class Program
{
private static void Main(string[] args)
{
Class1 class1 = new Class1() { Name = "Scott" };
Class2 class2 = new Class2() { Name = "Steve", Objects = new List<Class1>() { class1 } };
Class2 class22 = new Class2() { Name = "Atanas", Objects = new List<Class1>() { class1 } };
List<Class2> list = new List<Class2>() { class2, class22 };
string jSonString = JsonConvert.SerializeObject(list,Formatting.Indented,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
List<Class2> result = (List<Class2>) JsonConvert.DeserializeObject(jSonString, typeof(List<Class2>));
if (result[0].Objects[0] == result[1].Objects[0])
{
Console.WriteLine("Correct, its the same object");
}
else
{
Console.WriteLine("Bah!, its a new object");
}
}
}
public class Class1
{
public string Name { get; set; }
}
public class Class2
{
public Class2()
{
Objects = new List<Class1>();
}
public List<Class1> Objects { get; set; }
public string Name { get; set; }
}
The problem is that when the string is deserialized, the "Shared Object" is now duplicated. Before being serialized, the same object (by reference) was in two separate lists. After de serializing both the lists contain separate objects.
Is it possible to have json behave so it doesn't duplicate?
Hope that makes sense
Steve
Upvotes: 4
Views: 1761
Reputation: 1898
Yes, if you setup your serializer as follow:
JsonSerializerSettings settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All
};
Json string will be:
{
"$id": "1",
"$values": [
{
"$id": "2",
"Objects": {
"$id": "3",
"$values": [
{
"$id": "4",
"Name": "Scott"
}
]
},
"Name": "Steve"
},
{
"$id": "5",
"Objects": {
"$id": "6",
"$values": [
{
"$ref": "4"
}
]
},
"Name": "Atanas"
}
]
}
And you will see in console:
Correct, its the same object
Upvotes: 3