JSON.Net Ignore Property during deserialization

前端 未结 6 646
别跟我提以往
别跟我提以往 2020-12-29 19:55

I have a class set up as follows:

public class Foo
{
    public string string1 { get; set; }
    public string string2 { get; set; }
    public string string3         


        
6条回答
  •  孤独总比滥情好
    2020-12-29 20:25

    Here's the Newtonsoft Json preferred way to ignore a property without having to modify the class as based on http://james.newtonking.com/json/help/index.html?topic=html/ReducingSerializedJSONSize.htm

    This one is used to ignore lazy reference properties of EF or Linq2Sql

    public class DynamicContractResolver : DefaultContractResolver
    {
        protected override IList CreateProperties(Type type, 
            MemberSerialization memberSerialization)
        {
            Func includeProperty = t => t.IsValueType || t.Namespace.StartsWith("System") && t.Namespace.StartsWith("System.Data")==false; 
            IList properties = base.CreateProperties(type, memberSerialization);
            var allProperties = properties.Select (p => new{p.PropertyName,Including=includeProperty(p.PropertyType), p.PropertyType});//.Dump("props");
            var warnProperties=allProperties.Where (a =>a.Including && a.PropertyType.IsValueType==false && a.PropertyType.Name.IsIgnoreCaseMatch("String")==false) ;
    
            //linq pad debugging helper
            //var propertyTypesSerializing= allProperties.Where (p => p.Including).Select (p => p.PropertyType).Distinct().OrderBy (p => p.Name).Dump();
    
            if(warnProperties.Any())
            {
                //LinqPad helper
                //Util.Highlight(warnProperties.ToArray()).Dump("warning flag raised, aborting");
                throw new ArgumentOutOfRangeException();
            }
    
            properties = properties.Where(p =>includeProperty(p.PropertyType)).ToList();
            return properties;
        }
    }
    

    All the .Dump() calls are just linqpad debugging helpers, not needed method calls.

    sample usage:

    var inactives = from am in Aspnet_Memberships
            join mm in Member_members on am.UserId equals mm.Member_guid
            where mm.Is_active==false && mm.Org_id==1
            select new{am,mm};
            //inactives.Take(4).ToArray().Dump();
            var serialized = JsonConvert.SerializeObject(
                inactives.Skip(1).Select(i => i.mm).First(), 
                new  JsonSerializerSettings()
                {
                    ContractResolver = new DynamicContractResolver(), 
                    PreserveReferencesHandling = PreserveReferencesHandling.None,
                    ReferenceLoopHandling= ReferenceLoopHandling.Ignore
                }); 
                //.Dump();
    

提交回复
热议问题