【问题标题】:JsonProperty on C# Records in Constructor [duplicate]构造函数中 C# 记录上的 JsonProperty [重复]
【发布时间】:2021-03-03 00:24:41
【问题描述】:

对于 C# 9 中的新 C# 记录类型,我想知道是否可以(用于序列化)在构造函数参数上从 Newtonsoft.Json 设置 JsonPropertyAttribute。 它似乎不能开箱即用。

MWE:

using System;
using Newtonsoft.Json;

Console.WriteLine(JsonConvert.SerializeObject(new Something("something")));

record Something([JsonProperty("hello")] string world) {}

输出:

{"world":"something"}

预期输出:

{"hello":"something"}

有没有简单的方法让它像这样工作?还是我们必须使用真正的构造函数恢复到属性样式?

internal record Something
{
    public Something(string world) { World = world; }

    [JsonProperty("hello")] public string World { get; }
}

【问题讨论】:

    标签: c# .net json.net c#-9.0


    【解决方案1】:

    根据docs

    通过使用property:field: 目标,可以将属性应用于合成的自动属性及其支持字段,这些目标在语法上应用于相应的记录参数。

    所以你想要

    record Something([property:JsonProperty("hello")] string world) {}
    

    如果没有property: 限定符,属性最终会出现在生成的构造函数的参数上(这在其他场景中很有用,例如可空性)。

    【讨论】:

    • 在我最新的 VS19 预览中,没有 property: 编译中断,即 Attribute 'JsonIgnore' is not valid on this declaration type. It is only valid on 'property, indexer, field' declarations.
    • @kofifus:当然,但这与语法本身无关,但 JsonIgnore 有一个 AttributeUsage 属性,禁止在参数上使用。是否允许是特定于每个属性的。
    猜你喜欢
    • 1970-01-01
    • 2015-07-15
    • 2015-02-02
    • 2021-07-14
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    相关资源
    最近更新 更多