/// <summary> /// Reads the content of the Json file. /// </summary> /// <param name="filePath">path to the file</param> /// <returns><see cref="IEnumerable{JsonItem}"/> for all contained items.</returns> /// <remarks>An <see cref="Utf8JsonReader"/> instance cannot be created when using yield return iterator block.</remarks> public static IEnumerable <JsonItem> Parse(string filePath) { var rootItems = new List <JsonItem>(); var buffer = File.ReadAllBytes(filePath); var itemStack = new Stack <JsonItem>(); JsonItem currentProperty = null; var byteSequence = new ReadOnlySequence <byte>(buffer, 0, buffer.Length); var reader = new Utf8JsonReader(byteSequence); while (reader.Read()) { switch (reader.TokenType) { case JsonTokenType.StartObject: var newElement = new JsonElement(); if (null != currentProperty) { currentProperty.AddValue(newElement); } else if (0 < itemStack.Count) { var objectParent = (JsonItemArray)itemStack.Peek(); objectParent.AddValue(newElement); } itemStack.Push(newElement); currentProperty = null; break; case JsonTokenType.EndObject: var poppedObject = itemStack.Pop(); if (0 == itemStack.Count) { rootItems.Add(poppedObject); } break; case JsonTokenType.StartArray: var newArray = new JsonItemArray(); if (null != currentProperty) { currentProperty.AddValue(newArray); } else if (0 < itemStack.Count) { var arrayParent = (JsonItemArray)itemStack.Peek(); arrayParent.AddValue(newArray); } itemStack.Push(newArray); currentProperty = null; break; case JsonTokenType.EndArray: var poppedArray = itemStack.Pop(); if (0 == itemStack.Count) { rootItems.Add(poppedArray); } break; case JsonTokenType.PropertyName: var propertyName = reader.GetString(); var propertyParent = (JsonElement)itemStack.Peek(); currentProperty = propertyParent.CreateProperty(propertyName); break; case JsonTokenType.String: var stringValue = reader.GetString(); if (null != currentProperty) { currentProperty.AddValue(stringValue); currentProperty = null; } else { var stringParent = itemStack.Peek(); stringParent.AddValue(stringValue); } break; case JsonTokenType.Number: var doubleValue = reader.GetDouble(); if (null != currentProperty) { currentProperty.AddValue(doubleValue); currentProperty = null; } else { var doubleParent = itemStack.Peek(); doubleParent.AddValue(doubleValue); } break; } } return(rootItems); }