[Fork] How can I use default serialization inside a System.Text.Json JsonConverter?

CSharp · Console

/Program.cs

//https://stackoverflow.com/questions/65430420/how-to-use-default-serialization-in-a-custom-system-text-json-jsonconverter
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

using System.Text.Json;
using System.Text.Json.Serialization;

using NUnit.Framework; // Throws NUnit.Framework.AssertionException

//How can I use default serialization inside a System.Text.Json JsonConverter?
	
	public record Person(string FirstName, string LastName);

	public sealed class PersonConverter : JsonConverter<Person>
	{
		record PersonDTO(string FirstName, string LastName, string Name); // A DTO with both the old and new properties.
	
		public override Person Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			var dto = JsonSerializer.Deserialize<PersonDTO>(ref reader, options);
			var oldNames = dto?.Name?.Split(' ', StringSplitOptions.RemoveEmptyEntries) ?? Enumerable.Empty<string>();
			return new Person(dto.FirstName ?? oldNames.FirstOrDefault(), dto.LastName ?? oldNames.LastOrDefault());
		}

		public override void Write(Utf8JsonWriter writer, Person person, JsonSerializerOptions options)
			=> // What do I do here? I want to preserve other options such as options.PropertyNamingPolicy, which are lost by the following call
			JsonSerializer.Serialize(writer, person);
	}

    class TestClass
    {
        public static void Test()
        {
			foreach (var json in GetJson())
			{
				var options = new JsonSerializerOptions
				{
					PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
					Converters = { new PersonConverter() },
				};
				var person = JsonSerializer.Deserialize<Person>(json, options);
				var json2 = JsonSerializer.Serialize(person, options);

				Console.WriteLine(json);
				Console.WriteLine(person);
				Console.WriteLine(json2);
				Console.WriteLine();
				
				var person2 = JsonSerializer.Deserialize<Person>(json2, options);
				Assert.AreEqual(person, person2);
			}
		}	
		
		static IEnumerable<string> GetJson() =>
			new []
			{
				@"{""lastName"":""LastName"",""firstName"":""FirstName""}",
				@"{""name"":""Full Name""}",
			};
	}

	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 null;
		}
	}
;