Skip to content

Instantly share code, notes, and snippets.

@xiaoyvr
Created January 11, 2019 23:30
Show Gist options
  • Save xiaoyvr/97ad2b15a17ec6c61f30b6ecf8319bd7 to your computer and use it in GitHub Desktop.
Save xiaoyvr/97ad2b15a17ec6c61f30b6ecf8319bd7 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace MyNamespace
{
public class AutoPropertyAndFieldResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var jsonProperty = base.CreateProperty(member, memberSerialization);
var fieldInfo = member as FieldInfo;
if (fieldInfo != null)
{
// if (fieldInfo.IsInitOnly)
{
jsonProperty.Writable = true;
}
jsonProperty.Readable = true;
}
var property = member as PropertyInfo;
if (property != null)
{
jsonProperty.Ignored = !IsAutoInstanceProperty(property);
}
return jsonProperty;
}
private static bool IsAutoInstanceProperty(PropertyInfo property)
{
if (property.GetGetMethod() != null && !property.GetGetMethod().HasAttribute<CompilerGeneratedAttribute>())
{
return false;
}
Debug.Assert(property.DeclaringType != null, "property.DeclaringType != null");
var relativeFields = property.DeclaringType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
return relativeFields.Any(f => f.Name.Contains(property.Name) && f.Name.Contains("BackingField") && f.HasAttribute<CompilerGeneratedAttribute>());
}
protected override List<MemberInfo> GetSerializableMembers(Type objectType)
{
var members = objectType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Cast<MemberInfo>()
.Union(objectType.GetAllInstanceFields().Where(f => !f.HasAttribute<CompilerGeneratedAttribute>()))
.ToList();
return members;
}
}
public static class MemberInfoExtension
{
public static bool HasAttribute<T>(this MemberInfo memberInfo)
{
return memberInfo.GetCustomAttributes(typeof(T), true).Any();
}
public static IEnumerable<FieldInfo> GetAllInstanceFields(this Type t)
{
if (t == null)
return Enumerable.Empty<FieldInfo>();
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;
return t.GetFields(flags).Concat(GetAllInstanceFields(t.BaseType));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment