using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Text.Json.Serialization;
public static partial class JsonExtensions
public static JsonDocument JsonDocumentFromObject<TValue>(TValue value, JsonSerializerOptions options = default)
=> JsonDocumentFromObject(value, typeof(TValue), options);
public static JsonDocument JsonDocumentFromObject(object value, Type type, JsonSerializerOptions options = default)
var bytes = JsonSerializer.SerializeToUtf8Bytes(value, type, options);
return JsonDocument.Parse(bytes);
public static JsonElement JsonElementFromObject<TValue>(TValue value, JsonSerializerOptions options = default)
=> JsonElementFromObject(value, typeof(TValue), options);
public static JsonElement JsonElementFromObject(object value, Type type, JsonSerializerOptions options = default)
using var doc = JsonDocumentFromObject(value, type, options);
return doc.RootElement.Clone();
public string Data { get; set; }
public static void Test()
using var doc = JsonExtensions.JsonDocumentFromObject(new MyClass { Data = "value" });
Console.WriteLine(doc.RootElement);
var element = JsonExtensions.JsonElementFromObject(new MyClass { Data = "value" });
Console.WriteLine(element);
public static void Main()
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("System.Text.Json version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");
public static string GetNetCoreVersion()
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];