使用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; }
}
property:
,编译会出错,例如Attribute 'JsonIgnore' is not valid on this declaration type. It is only valid on 'property, indexer, field' declarations.
- kofifusJsonIgnore
有一个AttributeUsage
属性,禁止在参数上使用。是否允许这样做取决于具体的属性。 - Jeroen Mostert