Last active
November 11, 2024 14:56
-
-
Save Aetopia/5fb525d97b07423b26c6c36cc1d8293e to your computer and use it in GitHub Desktop.
JSON Document Object Model for .NET Framework.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace System.Runtime.Serialization.Json; | |
using System.IO; | |
using System.Xml; | |
using System.Linq; | |
using System.Text; | |
using System.Xml.Linq; | |
using System.Collections; | |
using System.Collections.Generic; | |
public readonly struct JsonNode : IEnumerable<JsonNode> | |
{ | |
public enum JsonType { Value, Array, Object } | |
readonly XElement Element; | |
readonly JsonType Type; | |
public JsonNode() => throw new NotSupportedException(); | |
JsonNode(XElement _) => Type = (Element = _).Attribute("type").Value[0] switch | |
{ | |
'a' => JsonType.Array, | |
'o' => JsonType.Object, | |
_ => JsonType.Value | |
}; | |
public static JsonNode Parse(string value) => Parse(Encoding.Unicode.GetBytes(value)); | |
public static JsonNode Parse(byte[] value) | |
{ | |
using var reader = JsonReaderWriterFactory.CreateJsonReader(value, XmlDictionaryReaderQuotas.Max); | |
return new(XElement.Load(reader)); | |
} | |
public static JsonNode Parse(Stream value) | |
{ | |
using var reader = JsonReaderWriterFactory.CreateJsonReader(value, XmlDictionaryReaderQuotas.Max); | |
return new(XElement.Load(reader)); | |
} | |
public readonly string Value => | |
Type is JsonType.Value ? Element.Value : throw new InvalidOperationException(); | |
public readonly JsonNode this[string value, bool _ = false] => | |
new(Type is JsonType.Object ? (_ ? Element.Descendants() : Element.Elements()).First(_ => Name(_) == value) : throw new InvalidOperationException()); | |
public readonly JsonNode this[int value] => | |
new(Type is JsonType.Array ? Element.Elements().ElementAt(value) : throw new InvalidOperationException()); | |
static string Name(XElement _) => | |
string.IsNullOrEmpty(_.Name.NamespaceName) ? _.Name.LocalName : _.Attribute("item").Value; | |
public IEnumerator<JsonNode> GetEnumerator() => | |
Element.Elements().Select(_ => new JsonNode(_)).GetEnumerator(); | |
IEnumerator IEnumerable.GetEnumerator() => | |
GetEnumerator(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment