我有一個自定義類,看起來像這樣:Json.NET:如何使DefaultValueHandling僅適用於某些類型?
public class PartnerLoginOptions
{
public string Username { get; set; }
public string Password { get; set; }
public string DeviceModel { get; set; }
public string Version { get; set; }
public bool? IncludeUrls { get; set; }
public bool? ReturnDeviceType { get; set; }
public bool? ReturnUpdatePromptVersions { get; set; }
}
我想忽略任何bool?
成員默認值序列化時,卻保持字符串與空值。舉例來說,如果我有這樣的
var options = new PartnerLoginOptions
{
Username = null,
Password = "123",
IncludeUrls = null,
ReturnDeviceType = true
};
一個對象,然後序列化會導致這樣的:
{
"username": null,
"password": "123",
"deviceModel": null,
"version": null,
"returnDeviceType": true
}
這裏是我的代碼至今:
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
DefaultValueHandling = DefaultValueHandling.Ignore // this applies to strings too, not just bool?
};
return JsonConvert.SerializeObject(options, settings);
有什麼方式做到這一點,沒有單獨標記OptionalBool
財產與[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
?謝謝。