找到循环参考。类中的类数据类型的属性

时间:2013-12-24 04:35:26

标签: asp.net c#-4.0

 public class childrens     {
        public ICollection<childrens> children { get; set; }
        public data data { get; set; }
        public string id { get; set; }
        public string name { get; set; }
    } 


 public static childrens GetJsonData()
        {
            childrens rootNode = new childrens();
            rootNode.data = new data();
            rootNode.id = "root";
            rootNode.name = "Top Albums";

            childrens objChildren547 = new childrens();
            objChildren547.data = new data { playcount = 547, area = "547" };
            objChildren547.id = "artist_A Perfect Circle";
            objChildren547.name = "A Perfect Circle";
            rootNode.children = new List<childrens>();
            rootNode.children.Add(objChildren547);

            childrens objChildren276 = new childrens();
            objChildren276.data = new data { playcount = 276, artist = "A Perfect Circle", image = "http:\\/\\/userserve-ak.last.fm\\/serve\\/300x300\\/11403219.jpg", area = "276" };
            objChildren276.id = "album-Thirteenth Step";
            objChildren276.name = "Thirteenth Step";
            objChildren547.children = new List<childrens>();
            objChildren547.children.Add(objChildren276);

            childrens objChildren271 = new childrens();
            objChildren271.data = new data { playcount = 271, artist = "A Perfect Circle", image = "http:\\/\\/userserve-ak.last.fm\\/serve\\/300x300\\/11403219.jpg", area = "271" };
            objChildren271.id = "album-Mer De Noms";
            objChildren271.name = "Mer De Noms";
            objChildren547.children.Add(objChildren271);
            return rootNode;
        }

   [WebMethod]
        public static HttpResponseMessage GetJsonData()
        {
            var data = jsondata.GetJsonData();
            return new HttpResponseMessage { Content = new ObjectContent(typeof(childrens), data, new System.Net.Http.Formatting.JsonMediaTypeFormatter() { SerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, PreserveReferencesHandling = PreserveReferencesHandling.None, MaxDepth = 10 } }) };
            //return data;
        }

上面的代码给出了一个错误“找到循环参考”。我使用了属性引用处理,但它没有用。

如何使用NewtonSoft.Json Library对其进行序列化来实现此目的。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

您需要将ReferenceLoopHandling option of the serialization settings配置为ReferenceLoopHandling.Serialize。您将选项传递给我认为的JsonConvert.SerializeObject方法。