有没有一种方法可以使用Json.NET序列化器而不使用JsonIgnore属性来忽略仅获取属性?
JsonIgnore
例如,我有一个带有以下get属性的类:
public Keys Hotkey { get; set; } public Keys KeyCode { get { return Hotkey & Keys.KeyCode; } } public Keys ModifiersKeys { get { return Hotkey & Keys.Modifiers; } } public bool Control { get { return (Hotkey & Keys.Control) == Keys.Control; } } public bool Shift { get { return (Hotkey & Keys.Shift) == Keys.Shift; } } public bool Alt { get { return (Hotkey & Keys.Alt) == Keys.Alt; } } public Modifiers ModifiersEnum { get { Modifiers modifiers = Modifiers.None; if (Alt) modifiers |= Modifiers.Alt; if (Control) modifiers |= Modifiers.Control; if (Shift) modifiers |= Modifiers.Shift; return modifiers; } } public bool IsOnlyModifiers { get { return KeyCode == Keys.ControlKey || KeyCode == Keys.ShiftKey || KeyCode == Keys.Menu; } } public bool IsValidKey { get { return KeyCode != Keys.None && !IsOnlyModifiers; } }
我是否需要添加[JsonIgnore]所有这些属性(我也有许多其他类),还是有更好的方法来忽略所有仅获取属性?
[JsonIgnore]
您可以通过实现自定义IContractResolver并在序列化过程中使用它来实现。如果将子类化DefaultContractResolver,这将变得非常容易:
IContractResolver
DefaultContractResolver
class WritablePropertiesOnlyResolver : DefaultContractResolver { protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { IList<JsonProperty> props = base.CreateProperties(type, memberSerialization); return props.Where(p => p.Writable).ToList(); } }
这是一个演示如何使用它的测试程序:
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); } } }
这是上面的输出。请注意,只读属性LowerCaseName未包含在输出中。
LowerCaseName
{"Id":2,"Name":"Joe Schmoe"}