Question41159582 c-sharp-serialize-with-json-net-inherited-private-fields

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Reflection;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;


    // https://stackoverflow.com/questions/41159582/c-sharp-serialize-with-json-net-inherited-private-fields

    public class DeclaredFieldJsonConverter<T> : JsonConverter where T: new()
    {
        const string basePropertyName = "base";

        public override bool CanConvert(Type objectType)
        {
            return typeof(T).IsAssignableFrom(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;

            var jObj = JObject.Load(reader);

            existingValue = existingValue ?? new T();
            var type = existingValue.GetType();

            while (jObj != null && type != null)
            {
                var basejObj = jObj.ExtractPropertyValue(basePropertyName) as JObject;
                JsonObjectContract contract = (JsonObjectContract)DeclaredFieldContractResolver.Instance.ResolveContract(type);
                foreach (var jProperty in jObj.Properties())
                {
                    var property = contract.Properties.GetClosestMatchProperty(jProperty.Name);
                    if (property == null)
                        continue;
                    var value = jProperty.Value.ToObject(property.PropertyType, serializer);
                    property.ValueProvider.SetValue(existingValue, value);
                }
                type = type.BaseType;
                jObj = basejObj;
            }

            return existingValue;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            WriteJson(writer, value, value.GetType(), serializer);
        }

        void WriteJson(JsonWriter writer, object value, Type type, JsonSerializer serializer)
        {
            JsonObjectContract contract = (JsonObjectContract)DeclaredFieldContractResolver.Instance.ResolveContract(type);

            writer.WriteStartObject();
            foreach (var property in contract.Properties.Where(p => !p.Ignored))
            {
                writer.WritePropertyName(property.PropertyName);
                serializer.Serialize(writer, property.ValueProvider.GetValue(value));
            }

            var baseType = type.BaseType;
            if (baseType != null && baseType != typeof(object))
            {
                writer.WritePropertyName(basePropertyName);
                WriteJson(writer, value, baseType, serializer);
            }

            writer.WriteEndObject();
        }
    }

    public static class JsonExtensions
    {
        public static JToken ExtractPropertyValue(this JObject obj, string name)
        {
            if (obj == null)
                return null;
            var property = obj.Property(name);
            if (property == null)
                return null;
            var value = property.Value;
            property.Remove();
            property.Value = null;
            return value;
        }
    }

    class DeclaredFieldContractResolver : DefaultContractResolver
    {
        // As of 7.0.1, Json.NET suggests using a static instance for "stateless" contract resolvers, for performance reasons.
        // http://www.newtonsoft.com/json/help/html/ContractResolver.htm
        // http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Serialization_DefaultContractResolver__ctor_1.htm
        // "Use the parameterless constructor and cache instances of the contract resolver within your application for optimal performance."
        // See also https://stackoverflow.com/questions/33557737/does-json-net-cache-types-serialization-information
        static DeclaredFieldContractResolver instance;

        // Explicit static constructor to tell C# compiler not to mark type as beforefieldinit
        static DeclaredFieldContractResolver() { instance = new DeclaredFieldContractResolver(); }

        public static DeclaredFieldContractResolver Instance { get { return instance; } }

        protected override List<MemberInfo> GetSerializableMembers(Type objectType)
        {
            var fields = objectType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly).Where(f => !f.IsNotSerialized);
            return fields.Cast<MemberInfo>().ToList();
        }

        protected override JsonObjectContract CreateObjectContract(Type objectType)
        {
            var contract = base.CreateObjectContract(objectType);
            contract.MemberSerialization = MemberSerialization.Fields;
            return contract;
        }

        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            return base.CreateProperties(type, MemberSerialization.Fields);
        }
    }

    public class Demo2
    {
        [NonSerialized]
        bool ShouldBeIgnored = true;

        private int count;
        public Demo2()
        {
            count = 2;
        }
    }
    public class MyDemo : Demo2
    {
        private int count;
        public MyDemo()
        {
            count = 3;
        }
    }

    class TestClass
    {
        public static void Test()
        {
            TestDemoRoundTrip();

            TestDemo();
        }

        static void TestDemo()
        {
            Console.WriteLine("Testing default serialization...");

            var demo = new MyDemo();

            var json = JsonConvert.SerializeObject(demo, new DeclaredFieldJsonConverter<MyDemo>());

            Console.WriteLine(json);

            var expectedJson = @"{""count"": 3, ""base"": {""count"":2}}";
            if (!JToken.DeepEquals(JToken.Parse(expectedJson), JToken.Parse(json)))
            {
                throw new InvalidOperationException("!JToken.DeepEquals(JToken.Parse(expectedJson), JToken.Parse(json))");
            }
            else
            {
                Console.WriteLine("Default serialization is as expected.");
            }
        }

        static void TestDemoRoundTrip()
        {
            Console.WriteLine("Testing round-trip with non-default values...");

            var json = @"{""count"": 33, ""base"": {""count"":22}}";
            var demo = JsonConvert.DeserializeObject<MyDemo>(json, new DeclaredFieldJsonConverter<MyDemo>());

            var json2 = JsonConvert.SerializeObject(demo, new DeclaredFieldJsonConverter<MyDemo>());
            Console.WriteLine(json2);

            if (!JToken.DeepEquals(JToken.Parse(json), JToken.Parse(json2)))
            {
                throw new InvalidOperationException("!JToken.DeepEquals(JToken.Parse(json), JToken.Parse(json2))");
            }
            else
            {
                Console.WriteLine(string.Format("{0} successfully round-tripped", demo));
            }
            // Assert that the NonSerialized property was not serialized.
            if (JObject.Parse(json2).SelectTokens("$..ShouldBeIgnored").Any())
            {
                throw new InvalidOperationException("JObject.Parse(json2).SelectTokens(\"$..ShouldBeIgnored\").Any()");
            }
        }
    }
					
	public class Program
	{
		public static void Main()
		{
            Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
			TestClass.Test();
		}
	}
;