问题描述
我想弄清楚如何为一个值创建一个属性 [NonSerialized]
看看这个:
using System;
using System.Text.Json;
class Test
{
public static bool GoingToBeSerialized = false;
public int PaymentForTheDay { get; set; }
public int NumberOfDays { get; set; }
// i want to disable it if GoingToBeSerialized is true
[System.Text.Json.Serialization.JsonIgnore]
public int TotalPayment;
public bool ShouldSerializeTotalPayment() => GoingToBeSerialized;
}
谢谢。
解决方法
请注意,[Serializable]
和 [NonSerialized]
(在原始问题中,现在已在编辑中删除)对大多数序列化程序没有任何作用 - 它们仅适用于 BinaryFormatter
,您没有使用。
很有可能只是使用:
public int TotalPayment {get;set;}
public bool ShouldSerializeTotalPayment() => GoingToBeSerialized;
会做你想做的;最近添加了显示您正在使用 Json.NET 的 pastebin,这确实应该有效 - conditional serialization is a Json.NET feature using the standard pattern。另请注意,我将 TotalPayment
设为 属性,并删除了 [JsonIgnore]
。