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.Buffers;
using System.Text.Json;
using System.Text.Json.Serialization;
using NUnit.Framework; // Throws NUnit.Framework.AssertionException
//https://stackoverflow.com/questions/58138793/system-text-json-jsonelement-toobject-workaround
// Alternatively, you might use ArrayPoolBufferWriter<byte>() from Microsoft.Toolkit.HighPerformance.Buffers
// using var bufferWriter = new ArrayPoolBufferWriter<byte>();
// https://docs.microsoft.com/en-us/dotnet/api/microsoft.toolkit.highperformance.buffers.arraypoolbufferwriter-1?view=win-comm-toolkit-dotnet-7.0
// https://github.com/CommunityToolkit/dotnet/blob/main/CommunityToolkit.HighPerformance/Buffers/ArrayPoolBufferWriter%7BT%7D.cs
public static partial class JsonExtensions
{
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 T ToObject<T>(this JsonDocument document, JsonSerializerOptions options = null)
{
if (document == null)
throw new ArgumentNullException(nameof(document));
return document.RootElement.ToObject<T>(options);
}
}
public class GlossDef
{
public string para { get; set; }
public List<string> GlossSeeAlso { get; set; }
}
public class GlossEntry
{
public string ID { get; set; }
public string SortAs { get; set; }
public string GlossTerm { get; set; }
public string Acronym { get; set; }
public string Abbrev { get; set; }
public GlossDef GlossDef { get; set; }
public string GlossSee { get; set; }
}
public class GlossList
{
public GlossEntry GlossEntry { get; set; }
}
public class GlossDiv
{
public string title { get; set; }
public GlossList GlossList { get; set; }
}
public class SomeClass
{
public string title { get; set; }
public GlossDiv GlossDiv { get; set; }
}
class TestClass
{
public static void Test()
{
var str = GetJson();
using var jDoc = JsonDocument.Parse(str);
var myClass = jDoc.RootElement.GetProperty("SomeProperty").ToObject<SomeClass>();
var newJson = JsonSerializer.Serialize(myClass, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(newJson);
}
static string GetJson()
{
var json = @"{
""SomeProperty"":{
""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""
}
}
}
}
}
";
return json;
}
}
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.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];
return null;
}
}