C#记录中的JsonProperty在构造函数中

21

使用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; }
}
1个回答

55
根据文档所述:

可通过为应用于相应记录参数的属性语法应用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
1
@kofifus:当然,但那与语法本身无关,而是因为JsonIgnore有一个AttributeUsage属性,禁止在参数上使用。是否允许这样做取决于具体的属性。 - Jeroen Mostert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接