构造函数中C#记录的JsonProperty [英] JsonProperty on C# Records in Constructor
本文介绍了构造函数中C#记录的JsonProperty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有了C#9中新的C#记录类型,我想知道是否有可能(用于序列化)在构造函数参数上设置Newtonsoft.Json的 JsonPropertyAttribute
.它似乎开箱即用.
With the new C# record types in C# 9 i'd like to know wheter it is possible (for serialization) to set the JsonPropertyAttribute
from Newtonsoft.Json on the constructor parameter.
It doesn't seem to work out of the box.
MWE:
using System;
using Newtonsoft.Json;
Console.WriteLine(JsonConvert.SerializeObject(new Something("something")));
record Something([JsonProperty("hello")] string world) {}
输出:
{"world":"something"}
预期输出:
{"hello":"something"}
有没有一种简单的方法可以使它像这样工作?还是我们必须使用真正的构造函数来还原为属性样式?
is there an easy way to make it work like this? or do we have to revert back to the property style with a real constructor?
internal record Something
{
public Something(string world) { World = world; }
[JsonProperty("hello")] public string World { get; }
}
推荐答案
查看全文