序列化属性,但不要在Json.Net中反序列化属性

虽然我发现了许多方法来反序列化特定属性,同时阻止它们序列化,但我正在寻找相反的行为。

我发现有很多问题要求反过来:

使用json.net进行属性反序列化但不能序列化

我可以指示Json.NET反序列化,但不能序列化特定属性吗?

JSON.Net – 仅在序列化时使用JsonIgnoreAttribute(但在反序列化时不使用)

如何序列化特定属性,但阻止它反序列化回POCO? 是否有可用于装饰特定属性的属性?

基本上我正在寻找与反序列化的ShouldSerialize *方法相当的方法。

我知道我可以写一个自定义转换器,但这似乎有点矫枉过正。

编辑:

这里有更多的背景。 这背后的原因是我的class级看起来像:

public class Address : IAddress { ///  /// Gets or sets the two character country code ///  [JsonProperty("countryCode")] [Required] public string CountryCode { get; set; } ///  /// Gets or sets the country code, and province or state code delimited by a vertical pipe: US|MI ///  [JsonProperty("countryProvinceState")] 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("provinceState")] [Required] public string ProvinceState { get; set; } } 

我需要CountryProvinceState属性作为请求,但我不希望它反序列化并触发setter逻辑。

最简单的方法是将属性标记为[JsonIgnore]并创建一个只获取代理属性:

  ///  /// Gets or sets the country code, and province or state code delimited by a vertical pipe: US|MI ///  [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来检查自定义属性。 如果找到,该属性将表示该属性是get-only:

 [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
(jsonString, settings);