/// <summary> /// Creates and returns a tree of JsonNode from JSON string. /// </summary> /// <param name="json">JSON string data.</param> /// <returns>Tree of JsonNode.</returns> public JsonNode GetJsonTree(string json) { json = json.Trim(); bool hasRootElement = !json.StartsWith("["); var root = new JsonNode(); if (hasRootElement) { root.Key = "root"; root.Path = "$"; } else { json = "{\"root\":" + json + "}"; root.Key = ""; root.Path = "$"; } root.ChildNodes = new List<JsonNode>(); dynamic jsonObj = JsonConvert.DeserializeObject<ExpandoObject>(json); AddChildNodes(root, jsonObj); return root; }
/// <summary> /// Recusively generates a tree of JsonNode. /// </summary> /// <param name="node">Parent node of current node.At beginning, root node is used.</param> /// <param name="jsonObj">Expando object of Value inside KeyValuePair of a deserialized JSON.</param> /// <param name="includeNonLeafnodeValues">This decides whether to show values of non leafnodes inside tree.</param> void AddChildNodes(JsonNode node, dynamic jsonObj, bool includeNonLeafnodeValues = false) { // Enumerating over it exposes the Properties and Values as a KeyValuePair foreach (KeyValuePair<string, object> kvp in jsonObj) { if (kvp.Value.GetType() == typeof(List<Object>)) { // kvp.Value is an array of objects. var values = (List<Object>)kvp.Value; int index = 0; // For each object, add a new node to the tree. foreach (var value in values) { if (value == null) continue; var newNode = new JsonNode(); newNode.Key = kvp.Key; //if(string.IsNullOrEmpty(node.Key)) // newNode.Path = string.Format("{0}[{1}]", node.Path, index++); //else newNode.Path = string.Format("{0}.[\"{1}\"][{2}]", node.Path, newNode.Key, index++); // If value is string, use it as node value. if (value is string) { newNode.Value = value.ToString(); } else { if (includeNonLeafnodeValues) { // If value is object, serialize it and save it as newNode value. newNode.Value = JsonConvert.SerializeObject(value); } // Add its child nodes of object to newNode. newNode.ChildNodes = new List<JsonNode>(); AddChildNodes(newNode, value); } // Add new node to the tree. node.ChildNodes.Add(newNode); } } else if (kvp.Value is ExpandoObject) { // kvp.Value is an object that contains other objects. var newNode = new JsonNode(); newNode.Key = kvp.Key; newNode.ChildNodes = new List<JsonNode>(); newNode.Path = string.Format("{0}.[\"{1}\"]", node.Path, newNode.Key); // If value is ExpandoObject, serialize it and save it as newNode value. newNode.Value = JsonConvert.SerializeObject(kvp.Value); AddChildNodes(newNode, kvp.Value); // Add new node to the tree. node.ChildNodes.Add(newNode); } else { // kvp.Value is a single object (leaf node) var newNode = new JsonNode(); newNode.Key = kvp.Key; newNode.Value = kvp.Value.ToString(); newNode.Path = string.Format("{0}.[\"{1}\"]", node.Path, newNode.Key); // Add new node to the tree. node.ChildNodes.Add(newNode); } } }