c# - 如何使用 System.Text.Json 忽略常量属性的 JSON 序列化?

标签 c# json json.net system.text.json

我正在尝试从 Newtonsoft.Json 迁移到 System.Text.Json。 “[Newtonsoft.Json.JsonIgnore]”适用于在序列化期间忽略常量属性,但“[System.Text.Json.Serialization.JsonIgnore]”则不然。我想知道是否有解决办法。

所以我正在尝试迁移;

using Newtonsoft.Json;

public class MyClass: MyBaseClass
{
    [JsonIgnore]
    public const string MyConstString = "lets get rid of netwonsoft dependency";

    public string data;

    public String(string data)
    {
        this.data = data;
    }
}

至;

using System.Text.Json.Serialization;

public class MyClass: MyBaseClass
{
    [JsonIgnore] // Error
    public const string MyConstString = "lets get rid of netwonsoft dependency";

    public string data;

    public String(string data)
    {
        this.data = data;
    }
}

错误描述为; “属性“JsonIgnore”在此声明类型上无效。它仅在“属性,索引器”声明上有效。”

是因为 System.Text.Json 不支持 JsonIgnore 的这种使用,还是我遗漏了一些东西? 我找不到任何有用的东西link关于这个问题。你有什么想法吗?

最佳答案

JSON.Net [JsonIgnore]属性有 usage设置为 AttributeTargets.Property | AttributeTargets.Field 意味着它可以在 const 上使用。然而,新的 .NET Core API 版本 [JsonIgnore]仅设置为 AttributeTargets.Property。这意味着您只能在属性上使用它。

话虽如此,JSON.Net 不会序列化 const 值,除非您明确告诉它使用 [JsonProperty] 进行序列化。属性,这使得添加另一个属性来忽略它有点奇怪。

例如,JSON.Net 会将您问题中的类序列化为:

{"data":"foo"}

System.Text.Json 中的序列化程序将为您提供以下信息:

{}

所以另一个问题是新的 API 不序列化字段。由此得出的结论是,您应该使用现代 C# 技术,这意味着使用属性,例如:

public string data { get; set; }

关于c# - 如何使用 System.Text.Json 忽略常量属性的 JSON 序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60529871/

相关文章:

c# - HTML Agility - 寻找正确的节点

c# - 如何在 Json.NET 中使用 JsonSerializerSettings 在属性中指定时禁用 TypeNameHandling?

c# - JSON.NET 反序列化为带有 Type 参数的对象

c# - 检测到 JSON.Net 自引用循环

c# - 在lync sdk 2013中检测音频设备并控制其音量

c# - 将构造函数参数从接口(interface)类型转换为具体类类型在这里是错误的吗?

php - jquery 构建数组不起作用

json - 解析云代码 afterSave 返回错误 107 无法 POST

javascript - 如何浏览这个 JSON 对象并获取它的值?

c# - UI繁忙时更改光标