[Fork] https://stackoverflow.com/questions/67707119/ignoring-jsonconverter-attribute-for-one-serialisation-call

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 System.Threading;
using System.Runtime.Serialization;

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/67707119/ignoring-jsonconverter-attribute-for-one-serialisation-call

	public partial class MyJsonClass 
	{
		public MyJsonClass x { get; set; }
	}
		
	[JsonConverter(typeof(MyConverter))]
	public partial class MyJsonClass 
	{
		[OnSerializing]
		void OnSerializingMethod(StreamingContext context) => MyConverter.PushDisabled(false); // Re-enable the converter after we begin to serialize the object

		[OnSerialized]
		void OnSerializedMethod(StreamingContext context) => MyConverter.PopDisabled(); // Restore the converter to its previous state when serialization is complete

		[OnDeserializing] 
		void OnDeserializingMethod(StreamingContext context) => MyConverter.PushDisabled(false); // Re-enable the converter after we begin to deserialize the object

		[OnDeserialized]
		void OnDeserializedMethod(StreamingContext context) => MyConverter.PopDisabled(); // Restore the converter to its previous state when deserialization is complete
	}

	sealed class MyConverter : RecursiveConverterBase<MyJsonClass, MyConverter>
	{
		class DTO { public MyJsonClass MyJsonClass { get; set; } }
	
		protected override void WriteJsonWithDefault(JsonWriter writer, object value, JsonSerializer serializer)
		{
			// Add your custom logic here.
			writer.WriteStartObject();
			writer.WritePropertyName(nameof(DTO.MyJsonClass));
			serializer.Serialize(writer, value);
			writer.WriteEndObject();
		}

		protected override object ReadJsonWithDefault(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			using (var pushValue = PushDisabledUsing(true))
			{
				// Add your custom logic here.
				return serializer.Deserialize<DTO>(reader)?.MyJsonClass;
			}
		}
	}

	public abstract class RecursiveConverterBase<TValue, TConverter> : JsonConverter where TConverter : RecursiveConverterBase<TValue, TConverter>
	{
		static readonly ThreadLocal<Stack<bool>> disabledStack = new (() => new Stack<bool>());
	
		public static StackExtensions.PushValue<bool> PushDisabledUsing(bool disable) => disabledStack.Value.PushUsing(disable);
		public static void PushDisabled(bool disable)
		{
			if (InSerialization)
				disabledStack.Value.Push(disable);
		}
		public static void PopDisabled()
		{
			if (InSerialization)
				disabledStack.Value.Pop();
		}
		static bool Disabled => disabledStack.IsValueCreated && disabledStack.Value.TryPeek(out var disabled) && disabled;
		static bool InSerialization => disabledStack.IsValueCreated && disabledStack.Value.Count > 0;

		public override bool CanRead => !Disabled;
		public override bool CanWrite => !Disabled;

		public override bool CanConvert(Type objectType) => typeof(TValue).IsAssignableFrom(objectType); // Or typeof(TValue) == objectType if you prefer.

		protected abstract void WriteJsonWithDefault(JsonWriter writer, object value, JsonSerializer serializer);

		public sealed override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			using (var pushValue = PushDisabledUsing(true))
			{
				WriteJsonWithDefault(writer, value, serializer);
			}
		}

		protected abstract object ReadJsonWithDefault(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer);

		public sealed override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			using (var pushValue = PushDisabledUsing(true))
			{
				return ReadJsonWithDefault(reader, objectType, existingValue, serializer);
			}
		}
	}

    public static class StackExtensions
    {
        public class PushValue<T> : IDisposable
        {
            readonly Stack<T> stack;
			readonly int count;

            public PushValue(T value, Stack<T> stack)
            {
                this.stack = stack;
				this.count = stack.Count;
                stack.Push(value);
            }

            // By using a disposable struct we avoid the overhead of allocating and freeing an instance of a finalizable class.
            public void Dispose()
            {
                if (stack != null)
				{
					while (stack.Count > count)
                    	stack.Pop();
				}
            }
        }

        public static PushValue<T> PushUsing<T>(this Stack<T> stack, T value)
        {
            if (stack == null)
                throw new ArgumentNullException();
            return new PushValue<T>(value, stack);
        }
    }
	
	public static class MyJsonClassExtensions
	{
		public static int Depth(this MyJsonClass value) => value == null ? 0 : 1 + (value.x?.Depth()).GetValueOrDefault(0);
	}
	
    class TestClass
    {
        public static void Test()
        {
			var myClass = new MyJsonClass
			{
				x = new MyJsonClass
				{
					x = new MyJsonClass { }
				},
			};
			
			var json = JsonConvert.SerializeObject(myClass, Formatting.Indented);
			
			Console.WriteLine(json);
			
			var root2 = JsonConvert.DeserializeObject<MyJsonClass>(json);
			
			root2.Dump();
			
			Assert.AreEqual(myClass.Depth(), root2.Depth());
		}	
	}

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