您可以通过实现自定义
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未包含在输出中。
{"Id":2,"Name":"Joe Schmoe"}


