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

后端 未结 4 1204
不知归路
不知归路 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:38

    You can do this by implementing a custom IContractResolver and using that during serialization. If you subclass the DefaultContractResolver, this becomes very easy to do:

    class WritablePropertiesOnlyResolver : DefaultContractResolver
    {
        protected override IList CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList props = base.CreateProperties(type, memberSerialization);
            return props.Where(p => p.Writable).ToList();
        }
    }
    

    Here is a test program demonstrating how to use it:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Serialization;
    
    class Program
    {
        static void Main(string[] args)
        {
            Widget w = new Widget { Id = 2, Name = "Joe Schmoe" };
    
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                ContractResolver = new WritablePropertiesOnlyResolver()
            };
    
            string json = JsonConvert.SerializeObject(w, settings);
    
            Console.WriteLine(json);
        }
    }
    
    class Widget
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string LowerCaseName
        {
            get { return (Name != null ? Name.ToLower() : null); }
        }
    }
    

    Here is the output of the above. Notice that the read-only property LowerCaseName is not included in the output.

    {"Id":2,"Name":"Joe Schmoe"}
    

提交回复
热议问题