最简单的方法是将real属性标记为,
[JsonIgnore]并创建一个get-
only代理属性:
/// <summary> /// Gets or sets the country pre, and province or state pre delimited by a vertical pipe: <c>US|MI</c> /// </summary> [JsonIgnore] public string CountryProvinceState { get { return string.Format("{0}|{1}", this.CountryCode, this.ProvinceState); } set { if (!string.IsNullOrWhiteSpace(value) && value.Contains("|")) { string[] valueParts = value.Split('|'); if (valueParts.Length == 2) { this.CountryCode = valueParts[0]; this.ProvinceState = valueParts[1]; } } } } [JsonProperty("countryProvinceState")] string ReadCountryProvinceState { get { return CountryProvinceState; } }如果需要,代理属性可以是私有的。
更新资料
如果必须对许多类中的许多属性执行此操作,则可能会更容易创建自己的
ContractResolver检查自定义属性的属性。如果找到,则该属性将表示该属性为仅获取:
[System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = false)]public class GetonlyJsonPropertyAttribute : Attribute{}public class GetonlyContractResolver : DefaultContractResolver{ protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { var property = base.CreateProperty(member, memberSerialization); if (property != null && property.Writable) { var attributes = property.AttributeProvider.GetAttributes(typeof(GetOnlyJsonPropertyAttribute), true); if (attributes != null && attributes.Count > 0) property.Writable = false; } return property; }}然后像这样使用它:
[JsonProperty("countryProvinceState")][GetOnlyJsonProperty]public string CountryProvinceState { get; set; }然后:
var settings = new JsonSerializerSettings { ContractResolver = new GetonlyContractResolver() }; var address = JsonConvert.DeserializeObject<Address>(jsonString, settings);


