这个问题在这里已经有了答案:
How do I target attributes for a record class?
(1 个回答)
8 个月前关闭。
使用 C# 9 中的新 C# 记录类型,我想知道是否可以(用于序列化)设置 JsonPropertyAttribute
来自 Newtonsoft.Json 的构造函数参数。
它似乎不是开箱即用的。
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; }
}
最佳答案
每 docs :
Attributes can be applied to the synthesized auto-property and its backing field by using
property:
orfield:
targets for attributes syntactically applied to the corresponding record parameter.
所以你要
record Something([property:JsonProperty("hello")] string world) {}
没有 property:
限定符,该属性最终位于生成的构造函数的参数上(这在其他场景中很有用,例如可空性)。
关于c# - 构造函数中 C# 记录上的 JsonProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64915034/