Issue
The problem I'm having is that when returning "treeNode" after building it, it doesn't serialize when sent down the wire via API. The object [and nested elements] looks great while debugging but when the browser receives the data for the tree it's converted to empty arrays (some with the correct length when there is more deeply nested child nodes). Any help is appreciated, see code and output below.
Running:
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 (tree/hierarchy building class):
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;
}
}
}
}
Output (before serialization):