How Do You “Really” Serialize Circular Referencing Objects With Newtonsoft.Json?

前端 未结 2 1697
无人共我
无人共我 2020-12-10 03:04

I\'m having a problem getting some data serialized correctly from my ASP.NET Web API controller using Newtonsoft.Json.

Here\'s what I think is going on -

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-10 03:16

    I wrote a minimal program to test this. Here is my github: https://github.com/assafwo1/TestSerializeJsonObjects. Here is the code:

    using Newtonsoft.Json;
    using System.Diagnostics;
    
    namespace TestSerializeJsonObjects
    {
        class Program
        {
            public class Node
            {
                public Node Next { get; set; }
            }
            static void Main(string[] args)
            {
                // create new node
                var head = new Node();
                // point its "next" field at itself
                head.Next = head;
                // this is now the smallest circular reference data structure possible 
                // assert that head next is head
                Debug.Assert(head.Next == head);
                // save to string
                var s = JsonConvert.SerializeObject(head, new JsonSerializerSettings
                {
                    PreserveReferencesHandling = PreserveReferencesHandling.Objects
                });
                // get from string
                var head2 = JsonConvert.DeserializeObject(s, new JsonSerializerSettings
                {
                    PreserveReferencesHandling = PreserveReferencesHandling.Objects
                });
                // assert that head2 next is head2
                Debug.Assert(head2.Next == head2);
                // done
            }
        }
    }
    

提交回复
热议问题