CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Collections.ObjectModel;
using System.Text.Json;
using System.Text.Json.Serialization;
using NUnit.Framework; // Throws NUnit.Framework.AssertionException
//https://stackoverflow.com/questions/70096362/force-system-text-json-to-deserialize-in-camelcase
#nullable enable
public class JsonElementConverter : JsonConverter<JsonElement>
{
public override void Write(Utf8JsonWriter writer, JsonElement value, JsonSerializerOptions options)
{
switch (value.ValueKind)
{
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);
}
writer.WriteEndObject();
break;
case JsonValueKind.Array:
writer.WriteStartArray();
foreach (var item in value.EnumerateArray())
Write(writer, item, options);
writer.WriteEndArray();
break;
default:
value.WriteTo(writer);
break;
}
}
public override JsonElement Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
using var doc = JsonDocument.ParseValue(ref reader);
return doc.RootElement.Clone();
}
}
class TestClass
{
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,
WriteIndented = true // Or false, if you prefer
};
Test(doc, options);
var options2 = new JsonSerializerOptions
{
Converters = { new JsonElementConverter() },
WriteIndented = true // Or false, if you prefer
};
Test(doc, options2);
Test(doc, new JsonSerializerOptions { }); // Not indented
}
public static void Test(JsonDocument doc, JsonSerializerOptions options)
{
var serialized = JsonSerializer.Serialize(doc.RootElement, options);
Console.WriteLine(serialized);
}
static string GetJson() => @"
{
""Glossary"": [[{
""Title"": ""example glossary"",
""GlossDiv"": {
""Title"": ""S"",
""GlossList"": {
""GlossEntry"": {
""ID"": ""SGML"",
""SortAs"": ""SGML"",
""GlossTerm"": ""Standard Generalized Markup Language"",
""Acronym"": ""SGML"",
""Abbrev"": ""ISO 8879:1986"",
""GlossDef"": [[{
""Para"": ""A meta-markup language, used to create markup languages such as DocBook."",
""GlossSeeAlso"": [""GML"", ""XML""]
}]],
""GlossSee"": ""markup""
}
}
}
}]]
}
";
}
public class Program
{
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();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
public static string GetNetCoreVersion()
{
//https://techblog.dorogin.com/how-to-detect-net-core-version-in-runtime-ecd65ad695be
//
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];
return "";
}
}