【发布时间】:2018-07-30 23:14:54
【问题描述】:
问题
我遇到的问题是,在构建后返回“treeNode”时,通过 API 沿线路发送时它不会序列化。对象 [和嵌套元素] 在调试时看起来很棒,但是当浏览器接收到树的数据时,它会转换为空数组(当嵌套更深的子节点时,一些具有正确的长度)。任何帮助表示赞赏,请参阅下面的代码和输出。
跑步:
TreeNode<GenericClass> treeNode = new TreeNode<GenericClass>(new GenericClass() { Title = "Root", URL = null });
GenericClass Google = new GenericClass() { Title = "Google", URL = "https://www.google.com" };
GenericClass Yahoo = new GenericClass() { Title = "Yahoo", URL = "https://www.yahoo.com" };
GenericClass Bing = new GenericClass() { Title = "Bing", URL = "https://www.bing.com" };
treeNode.AddChild(Google);
treeNode.AddChild(Yahoo);
treeNode.AddChild(Bing);
// return treeNode.ToString(); <- Doesnt work
// return treeNode.ToList(); <- Doesnt work
// return JsonConvert.SerializeObject(treeNode); <-Doesnt work
return treeNode;
TreeNode(树/层次结构类):
public class TreeNode<T> : IEnumerable<TreeNode<T>>
{
#region Properties
public T Data { get; set; }
public TreeNode<T> Parent { get; set; }
public ICollection<TreeNode<T>> Children { get; set; }
public Boolean IsRoot
{
get { return Parent == null; }
}
public Boolean IsLeaf
{
get { return Children.Count == 0; }
}
public int Level
{
get
{
if (this.IsRoot)
{
return 0;
}
return Parent.Level + 1;
}
}
#endregion
public TreeNode(T data)
{
this.Data = data;
this.Children = new LinkedList<TreeNode<T>>();
this.ElementsIndex = new LinkedList<TreeNode<T>>();
this.ElementsIndex.Add(this);
}
public TreeNode<T> AddChild(T child)
{
TreeNode<T> childNode = new TreeNode<T>(child) { Parent = this };
this.Children.Add(childNode);
this.RegisterChildForSearch(childNode);
return childNode;
}
public override string ToString()
{
return Data != null ? Data.ToString() : "[data null]";
}
private ICollection<TreeNode<T>> ElementsIndex { get; set; }
private void RegisterChildForSearch(TreeNode<T> node)
{
ElementsIndex.Add(node);
if (Parent != null)
{
Parent.RegisterChildForSearch(node);
}
}
public TreeNode<T> FindTreeNode(Func<TreeNode<T>, bool> predicate)
{
return this.ElementsIndex.FirstOrDefault(predicate);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<TreeNode<T>> GetEnumerator()
{
yield return this;
foreach (var directChild in this.Children)
{
foreach (var anyChild in directChild)
{
yield return anyChild;
}
}
}
}
输出(序列化前):
【问题讨论】:
-
序列化怎么样?
-
当你写
return JsonConvert.SerializeObject(treeNode); doesn't work时,你说的不起作用是什么意思,有例外吗?或者,这会返回一个您不喜欢其格式的字符串吗? -
是的,它确实给出了异常 -> Newtonsoft.Json.JsonSerializationException:检测到类型为“TreeNode”的自引用循环
标签: c# generics serialization ienumerable icollection