强制序列化具有[JsonIgnore]属性

时间:2018-04-27 08:10:25

标签: c# json.net

是否有可能以某种方式强制x属性的序列化?

public class Cake
{
    [JsonIgnore]
    // possibly some attribute like [ReadOnlyJsonIgnore] or [JsonIgnoreReadOnly] would be nice
    public int x { get; set; }
}

但是只保留[JsonIgnore]进行反序列化?我想要实现的是某种形式的只读属性。所以它们可以被序列化,但不能被反序列化,只是被忽略,就像它们不存在一样。

1 个答案:

答案 0 :(得分:0)

好吧,我做了什么让这个“力量”工作(有点hackish):

我创建的自定义new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='bootstrap-dialog-footer-buttons']//button[@class='btn btn-warning']"))).click(); 使用自定义JsonConverter,仅在IContractResolver中写入时忽略[JsonIgnore]

WriteJson

但对于public class CustomJsonConverter : JsonConverter { ... public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { // somehow using serializer passed to this method doesn't seem to work var token = JToken.FromObject(value, new JsonSerializer() { ContractResolver = new DontIgnoreContractResolver() }); token.WriteTo(writer); } } public class DontIgnoreContractResolver : DefaultContractResolver { protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { var jsonProperty = base.CreateProperty(member, memberSerialization); if (jsonProperty.Ignored) { jsonProperty.Ignored = false; } return jsonProperty; } } ,它使用默认合约解析程序并忽略该属性。但是,这是可能的。