构造函数中C#记录的JsonProperty [英] JsonProperty on C# Records in Constructor

查看:37
本文介绍了构造函数中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; }
}

推荐答案

每个

属性可以通过使用 property: field:目标来语法地应用于相应的记录参数,从而应用于合成的自动属性及其支持字段.

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:限定符,则该属性最终位于生成的构造函数的参数上(这在其他情况下很有用,例如可空性).

Without the property: qualifier, the attribute ends up on the parameter of the generated constructor (which is useful in other scenarios, like nullability).

这篇关于构造函数中C#记录的JsonProperty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆