c# - 为值设置属性 [NonSerialized]

标签 c# json-serialization

我试图弄清楚如何为值创建属性 [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;
}

谢谢。

最佳答案

请注意,[Serialized][NonSerialized](在原始问题中,现已在编辑中删除)对大多数序列化器没有任何作用- 它们仅适用于您没有使用的 BinaryFormatter

很有可能简单地使用:

public int TotalPayment {get;set;}
public bool ShouldSerializeTotalPayment() => GoingToBeSerialized;

会做你想做的事;最近添加的 Pastebin 显示您正在使用 Json.NET,这确实应该有效 - conditional serialization is a Json.NET feature using the standard pattern 。另请注意,我将 TotalPayment 设为属性,并删除了 [JsonIgnore]

关于c# - 为值设置属性 [NonSerialized],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67667924/

相关文章:

c# - AspNet Core - Controller 级别的输入/输出 JSON 序列化设置

json - iOS (Swift) 中使用 JSONSerialization 的 PUT 请求

ios - 从 (_,_,_) 类型的抛出函数 throws -> Void 到非抛出函数类型 (NSData?, NSURLResponse?, NSError?) -> Void 的无效转换

c# - IList<object[]> XmlSerializer 与通用列表的序列化

c# - LINQ 查询很慢

c# - 从轮廓生成HALCON区域

ios - 将 JSON 响应概括为函数参数

c# - LINQ over XAML 提供程序

c# - 列表框无法识别 MouseLeftButtonDown?

c# - 将字符串转换为类型 'System.Text.Json.JsonElement 时出错