4

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

0

1 Answer 1

3

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

See http://james.newtonking.com/projects/json/help/index.html?topic=html/T_Newtonsoft_Json_PreserveReferencesHandling.htm

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.