【问题标题】:How to ignore JSON serialization of constant properties using System.Text.Json?如何使用 System.Text.Json 忽略常量属性的 JSON 序列化?
【发布时间】:2020-03-04 15:51:41
【问题描述】:

我正在尝试从 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' 在此声明类型上无效。它仅在 'property, indexer' 声明上有效。”

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

【问题讨论】:

  • 属性声明通常有一个 getter 和/或一个 setter。可以试试改成public string MyConstString { get; } = "your string";
  • System.Text.Json 无论如何都不会序列化 const,这里不需要该属性。
  • 事实上,Newtonsoft 也不会,不清楚为什么你的const 首先有这个属性?
  • 也许你遇到的一个更大的问题是新的序列化器不会序列化字段,这意味着你需要将它们更改为属性。
  • Newtonsoft 将仅在您使用 [JsonProperty] 属性明确标记它们时序列化 const 值。

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


【解决方案1】:

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

话虽如此,JSON.Net 不会序列化 const 值,除非您通过使用 [JsonProperty] 属性明确告诉它序列化,然后添加另一个属性以忽略它无论如何都会有点奇怪。

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

{"data":"foo"}

System.Text.Json 中的序列化程序会给你这个:

{}

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

public string data { get; set; }

【讨论】:

    猜你喜欢
    • 2023-02-01
    • 1970-01-01
    • 2019-08-02
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多