[Fork] https://stackoverflow.com/questions/66733995/c-sharp-serialize-protected-attributes-from-parent-class-issue

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/66733995/c-sharp-serialize-protected-attributes-from-parent-class-issue

	public class CommandResponse
	{
		protected string jsonTestProtected;
		
		protected string jsonTestProtectedGetOnlyProperty => jsonTestProtected;

		protected string jsonTestProtectedSetOnlyProperty { set { jsonTestProtected = value; } }
		
		[JsonIgnore] public string AmIIgnored => throw new NotImplementedException();
		
		public CommandResponse(string jsonTestProtected) => this.jsonTestProtected = jsonTestProtected;
	}

    class CommandActionInvalid : CommandResponse
    {
		public CommandActionInvalid(string jsonTestProtected): base(jsonTestProtected) { }
	
        private string jsonTestPrivate { get; set; } = "child-class";
	}

    class TestClass
    {
		static IContractResolver resolver = new CustomJsonContractResolver();
		
        public static void Test()
        {
			var cmd = new CommandActionInvalid("Attr from parent class");
			
			var settings = new JsonSerializerSettings
			{
				ContractResolver = resolver,
			};
			
			var json = JsonConvert.SerializeObject(cmd, Formatting.Indented, settings);
			
			Console.WriteLine(json);
		}	
	}

    class CustomJsonContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
    {
		const BindingFlags allInstanceMembersFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy;
	
		protected override List<MemberInfo> GetSerializableMembers(Type objectType)
		{
			IEnumerable<MemberInfo> fields = 
				objectType.GetFields(allInstanceMembersFlags)
					// Skip k__BackingField secret backing fields of auto-implemented properties.
					.Where(fi => !fi.IsDefined(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute)));
			IEnumerable<MemberInfo> props = objectType.GetProperties(allInstanceMembersFlags)
					// Skip indexed properties like List[0].
					.Where(pi => pi.GetIndexParameters().Length == 0);
			return fields.Concat(props).ToList();
		}
	
		protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
		{
			switch (member)
			{
				case FieldInfo fi:
					// Passing MemberSerialization.Fields causes the JsonProperty to be marked as readable and writable
					return base.CreateProperty(fi, MemberSerialization.Fields);
				case PropertyInfo pi:
					var jsonProperty = base.CreateProperty(pi, memberSerialization);
					// Mark the property as readable and writable if the corresponding get and set methods exist even if not public
					if (pi.GetGetMethod(true) != null)
						jsonProperty.Readable = true;
					if (pi.GetSetMethod(true) != null)
						jsonProperty.Writable = true;
					return jsonProperty;
				default:
					return base.CreateProperty(member, memberSerialization);
			}
		}
    }

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