JsonPropertyNameAttribute is not supported record from C#9? [duplicate]

耗尽温柔 提交于 2021-02-05 07:34:45

问题


I want to use record with JsonPropertyName attribute, but it caused an error. This is not supported? Any workaround?

public record QuoteResponse([JsonPropertyName("quotes")] IReadOnlyCollection<Quote>? Quotes);

Error CS0592 Attribute 'JsonPropertyName' is not valid on this declaration type. It is only valid on 'property, indexer, field' declarations.


回答1:


By default attributes on record parameters apply to the parameter. To make them apply to the property you have to prefix it with the property: attribute location:

public record QuoteResponse([property: JsonPropertyName("quotes")] IReadOnlyCollection<Quote>? Quotes);



回答2:


There are 2 ways (that I know of) to create a record, the below will hopefully solve it for you.

public record QuoteResponse
{
    [JsonPropertyName("quotes")]
    public IReadOnlyCollection<Quote>? Quotes {get; init;}
}


来源:https://stackoverflow.com/questions/65219551/jsonpropertynameattribute-is-not-supported-record-from-c9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!