【发布时间】: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; }
}
【问题讨论】: