c# - 构造函数中 C# 记录上的 JsonProperty

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

这个问题在这里已经有了答案:





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: or field: 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/

相关文章:

css - HTML 根据部署机器以不同方式引用我的 CSS

c# - 使用 Json.net 反序列化时为 "Unexpected token: StartObject"

c# - 强制对象以 "dd-mm-yyyy"格式序列化日期

c# - 静态一次性元素

c# - TextWriterTraceListener 不起作用

c# - WPF动画不流畅

.net - 正则表达式,以字母/_开头的字符串,以及(可能)字母/数字/_之后的字符串

c# - 在运行时动态创建从基类继承的对象

c# - Linq 查询和预期结果 -- 不同字段

C# JSON.NET 如何忽略反序列化中的属性而不是序列化中的属性