using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Collections.ObjectModel;
using System.Text.Json.Serialization;
public static partial class JsonExtensions
public static string ToString(this JsonElement element, bool indent)
=> element.ValueKind == JsonValueKind.Undefined ? "" : JsonSerializer.Serialize(element, new JsonSerializerOptions { WriteIndented = indent } );
public static void Test()
var defaultJson1 = default(JsonElement).ToString(true);
var defaultJson2 = default(JsonElement).ToString();
Assert.AreEqual(defaultJson2, defaultJson1);
using var doc = JsonDocument.Parse(GetJson());
var myJsonElement = doc.RootElement;
Test(myJsonElement, false);
Test(myJsonElement, true);
var indentedJson = myJsonElement.ToString(true);
static void Test(JsonElement myJsonElement, bool indent)
Console.WriteLine(myJsonElement.ToString(indent));
static string GetJson() => @"{
""title"": ""example glossary"",
""ID"": ""SGML"",""SortAs"": ""SGML"",""GlossTerm"": ""Standard Generalized Markup Language"",
""Abbrev"": ""ISO 8879:1986"",
""para"": ""A meta-markup language, used to create markup languages such as DocBook."",
""GlossSeeAlso"": [""GML"", ""XML""]
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];