// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.IO; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace E { public enum PathType { OBJECT_FIELD_NAME, ARRAY_INDEX } public class PathElement { public PathType Type { get; set; } public string Value { get; set; } public PathElement(int val) { this.Type = PathType.ARRAY_INDEX; this.Value = val.ToString(); } public PathElement(string val) { this.Type = PathType.OBJECT_FIELD_NAME; this.Value = val; } public override string ToString() { switch(Type) { case PathType.OBJECT_FIELD_NAME: return"object field name " + Value; case PathType.ARRAY_INDEX: return "array index " + Value; default: throw new Exception("Houston we have a problem"); } } } public class Path { private List elms; public Path() { this.elms = new List(); } public Path(List elms) { this.elms = elms; } public Path Append(PathElement elm) { List temp = this.elms.Select(p => p).ToList(); temp.Add(elm); return new Path(temp); } public override string ToString() { return string.Join(" ", this.elms); } public List GetElements() { return elms; } } public class JsonParser { public delegate void Handle(Path path, string val); private void Process(JToken tok, Path path, Handle h) { if(tok is JArray) { int ix = 0; foreach(JToken tok2 in tok as JArray) { Process(tok2, path.Append(new PathElement(ix)), h); ix++; } } else if(tok is JObject) { foreach(KeyValuePair f in tok as JObject) { Process(f.Value, path.Append(new PathElement(f.Key)), h); } } else if(tok is JValue) { h(path, (tok as JValue).Value.ToString()); } else { throw new Exception("Houston we have a problem"); } } public void Process(string fnm, Handle h) { Process((JToken)JsonConvert.DeserializeObject(File.ReadAllText(fnm)), new Path(), h); } } public class Program { private static void Print(Path path, string val) { Console.WriteLine("{0} = {1}", path, val); } public static void Main(string[] args) { JsonParser parser = new JsonParser(); parser.Process(@"\work\e4.json", Print); } } }