public static T ToObject <T>(this JsonElement element, JsonSerializerOptions?options = null) { var bufferWriter = new ArrayBufferWriter <byte>(); using (var writer = new Utf8JsonWriter(bufferWriter)) element.WriteTo(writer); return(JsonSerializer.Deserialize <T>(bufferWriter.WrittenSpan, options) !); }
public static async Task <T> ToObjectAsync <T>(this JsonElement element, JsonSerializerOptions?options = null) { ArrayBufferWriter <byte>?bufferWriter = new ArrayBufferWriter <byte>(); await using (Utf8JsonWriter writer = new Utf8JsonWriter(bufferWriter)) element.WriteTo(writer); return(JsonSerializer.Deserialize <T>(bufferWriter.WrittenSpan, options) !); }
/// <summary> /// Gets the json representation as string. /// </summary> /// <param name="json">The j.</param> /// <param name="options">The options.</param> /// <returns></returns> public static Stream ToStream( this JsonElement json, JsonWriterOptions options = default) { var ms = new MemoryStream(); using (var w = new Utf8JsonWriter(ms, options)) { json.WriteTo(w); } ms.Seek(0, SeekOrigin.Begin); return(ms); }
/// <summary> /// Gets the json representation as string. /// </summary> /// <param name="json">The j.</param> /// <param name="options">The options.</param> /// <returns></returns> public static string AsString( this JsonElement json, JsonWriterOptions options = default) { using var ms = new MemoryStream(); using (var w = new Utf8JsonWriter(ms, options)) { json.WriteTo(w); } var result = Encoding.UTF8.GetString(ms.ToArray()); return(result); }