Sample walker

CSharp · Console

/Program.cs

using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Collections.Generic;
using System.Linq;

public class Program
{
	public static void Main()
	{
		Console.WriteLine("Hello World");
		var json = "{\"name\":\"foo\",\"targetChildren\":[\"baz\",\"quux\"],\"valsFromChildren\":[],\"runtimeValsFromChildren\":[],\"childObjects\":[{\"name\":\"baz\",\"valToGive\":\"giftFromBaz\",\"targetChildren\":[\"qux\"],\"valsFromChildren\":[],\"runtimeValsFromChildren\":[],\"childObjects\":[{\"name\":\"qux\",\"valToGive\":\"giftFromQux\"},{\"name\":\"quux\",\"valToGive\":\"giftFromQuux\"}]}]}";
		var obj = JsonSerializer.Deserialize<JsonObj>(json);
		Console.WriteLine($@"Hello World {obj.Name} has {obj.TargetChildren.Count} targets");
		foreach (var item in obj.TargetChildren.Select((value, i) => new { i, value	}))
		{
			Console.WriteLine($@"Hello item: {item} has targets");
			var value = item.value;
			var index = item.i;
			Console.WriteLine($@"x: index:{index} val: {value} ");
		}

		DoRecursion(obj);
		var newObjJson = JsonSerializer.Serialize(obj);
			Console.WriteLine($@"serial {newObjJson} ");
		foreach (var rv in obj.RuntimeValsFromChildren)
		{
			Console.WriteLine($@"Count {rv} ");
		}

		foreach (var v in obj.ValsFromChildren)
		{
			Console.WriteLine($@"Vals {v} ");
		}
	}

	static JsonObj DoRecursion(JsonObj obj)
	{
		if (obj.ChildObjects == null || obj.ChildObjects.Count <= 0)
			return obj;
		foreach (var child in obj.ChildObjects)
		{
			Console.WriteLine($@"Hello Recursing  Name:{child.Name} Count: {obj.ChildObjects.Count} kiddos");
			var g = obj.ChildObjects.Where(co => co.Name == child.Name)
				.Select(x => new{Name= x.Name, Val= x.ValToGive}).First();
			Console.WriteLine($"g:{g.Name} v:{g.Val}");
			var newObjJson = JsonSerializer.Serialize(obj);
			var parent = obj;
			if (parent.TargetChildren != null && parent.TargetChildren.Contains(child.Name))
			{
				// Give the values to the parent that is targeting them.
				parent.ValsFromChildren.Add(child.ValToGive);
				parent.RuntimeValsFromChildren.Add(child.RuntimeVal);
			}

			return DoRecursion(child);
		}

		return obj;
	}

	class JsonObj
	{
		[JsonPropertyName("name")]
		public string Name { get; set; }

		[JsonPropertyName("valToGive")]
		public string ValToGive { get; set; }

		[JsonPropertyName("targetChildren")]
		public List<string> TargetChildren { get; set; }

		[JsonPropertyName("valsFromChildren")]
		public List<string> ValsFromChildren { get; set; }

		[JsonPropertyName("runtimeValsFromChildren")]
		public List<int> RuntimeValsFromChildren { get; set; }

		[JsonPropertyName("childObjects")]
		public List<JsonObj> ChildObjects { get; set; }

		[JsonIgnore]
		public int RuntimeVal => new Random().Next(0, 100);
	}
}
;