https://stackoverflow.com/questions/67420877/c-sharp-newtonsoft-json-custom-deserializer

CSharp · Console

/Program.cs

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 Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;	

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

//https://stackoverflow.com/questions/67420877/c-sharp-newtonsoft-json-custom-deserializer

	class Customer {
		[JsonConverter(typeof(WrapWithValueConverter<string>))]
		public string CustomerID { get; set; }
		[JsonConverter(typeof(WrapWithValueConverter<string>))]
		public string CustomerCurrencyID { get; set; }
	}

    public class WrapWithValueConverter<TValue> : JsonConverter
    {
		// Here we take advantage of the fact that a converter applied to a property has highest precedence to avoid an infinite recursion.
		class DTO { [JsonConverter(typeof(NoConverter))] public TValue value { get; set; } public object GetValue() => value; }

        public override bool CanConvert(Type objectType) => typeof(TValue).IsAssignableFrom(objectType);
		
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
			=> serializer.Serialize(writer, new DTO { value = (TValue)value });

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
			=> serializer.Deserialize<DTO>(reader)?.GetValue();
	}

    public class NoConverter : JsonConverter
    {
        // NoConverter taken from this answer https://stackoverflow.com/a/39739105/3744182
        // By https://stackoverflow.com/users/3744182/dbc
        // To https://stackoverflow.com/questions/39738714/selectively-use-default-json-converter
        public override bool CanConvert(Type objectType)  { throw new NotImplementedException(); /* This converter should only be applied via attributes */ }
        public override bool CanRead => false;
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) => throw new NotImplementedException();
        public override bool CanWrite => false;
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
    }

    class TestClass
    {
        public static void Test()
        {
			var json = GetJson();
			
			var model = JsonConvert.DeserializeObject<Customer>(json);
			
			model.Dump();

			Assert.AreEqual("USD", model.CustomerCurrencyID);
			Assert.AreEqual("EXAMPLE", model.CustomerID);
			
			var json2 = JsonConvert.SerializeObject(model, Formatting.Indented);
			
			Console.WriteLine(json2);
			
			Assert.IsTrue(JToken.DeepEquals(JToken.Parse(json), JToken.Parse(json2)));
		}	
		
		static string GetJson()
		{
			return @"{
    ""CustomerID"": {
        ""value"": ""EXAMPLE""
    },
    ""CustomerCurrencyID"": {
        ""value"": ""USD""
    }
}
";
		}
	}

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
			Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Assembly.GetName().Name,  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;
		}
	}
;