我正在尝试从 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/