I have to serialize derived class, but I need all data it contains (including private fields and base class ones).
I'd like to use [Datacontract]
as below.
using System;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace ConsoleApplication1
{
class Program
{
[DataContract]
class Base
{
public Base(int fieldValue)
{
_field = fieldValue;
}
[DataMember]
private int _field;
}
class Derived : Base
{
public Derived(int fieldValue) : base(fieldValue)
{
}
}
public static void Main(string[] args)
{
var derived = new Derived(10);
var serialized = JsonConvert.SerializeObject(derived);
Console.WriteLine(serialized);
}
}
}
But there are too much legacy classes to modify, so I followed the question and wrote Contract resolver
public class MyContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = type
.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(p => p.CanRead && p.CanWrite)
.Select(p => base.CreateProperty(p, memberSerialization))
.Union(type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Select(f => base.CreateProperty(f, memberSerialization)))
.Distinct(JsonPropertyComparer.Instance)
.ToList();
foreach (var property in properties)
{
var ignored = ShouldPropertyBeIgnored(property);
property.Ignored = ignored;
property.Readable = !ignored;
property.Writable = !ignored;
}
return properties;
}
// Actualy, contains some logic
private bool ShouldPropertyBeIgnored(JsonProperty property) => false;
}
Unfortunately, it does not serialise properties of base types