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 class JsonElementConverter : JsonConverter<JsonElement>
public override void Write(Utf8JsonWriter writer, JsonElement value, JsonSerializerOptions options)
case JsonValueKind.Object:
var policy = options.PropertyNamingPolicy;
writer.WriteStartObject();
foreach (var pair in value.EnumerateObject())
writer.WritePropertyName(policy?.ConvertName(pair.Name) ?? pair.Name);
Write(writer, pair.Value, options);
case JsonValueKind.Array:
writer.WriteStartArray();
foreach (var item in value.EnumerateArray())
Write(writer, item, options);
public override JsonElement Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
using var doc = JsonDocument.ParseValue(ref reader);
return doc.RootElement.Clone();
public static void Test()
var jsonString = GetJson();
using var doc = JsonDocument.Parse(jsonString);
JsonNamingPolicy policy = JsonNamingPolicy.CamelCase;
var options = new JsonSerializerOptions
Converters = { new JsonElementConverter() },
PropertyNamingPolicy = policy,
var options2 = new JsonSerializerOptions
Converters = { new JsonElementConverter() },
Test(doc, new JsonSerializerOptions { });
public static void Test(JsonDocument doc, JsonSerializerOptions options)
var serialized = JsonSerializer.Serialize(doc.RootElement, options);
Console.WriteLine(serialized);
static string GetJson() => @"
""Title"": ""example glossary"",
""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.Location.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];