Is there a way to ignore get-only properties in Json.NET without using JsonIgnore attributes?

后端 未结 4 1207
不知归路
不知归路 2020-11-29 05:19

Is there a way to ignore get-only properties using the Json.NET serializer but without using JsonIgnore attributes?

For example, I have a class with the

4条回答
  •  无人及你
    2020-11-29 05:47

    You can use a contract resolver like this:

    public class ExcludeCalculatedResolver : DefaultContractResolver
    {
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            var property = base.CreateProperty(member, memberSerialization);
            property.ShouldSerialize = _ => ShouldSerialize(member);
            return property;
        }
    
        internal static bool ShouldSerialize(MemberInfo memberInfo)
        {
            var propertyInfo = memberInfo as PropertyInfo;
            if (propertyInfo == null)
            {
                return false;
            }
    
            if (propertyInfo.SetMethod != null)
            {
                return true;
            }
    
            var getMethod = propertyInfo.GetMethod;
            return Attribute.GetCustomAttribute(getMethod, typeof(CompilerGeneratedAttribute)) != null;
        }
    }
    

    It will exclude calculated properties but include C#6 get only properties and all properties with a set method.

提交回复
热议问题