Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

enter image description here

like image 668
Make Makeluv Avatar asked Dec 09 '20 15:12

Make Makeluv


2 Answers

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);
like image 177
Yair Halberstadt Avatar answered Oct 17 '22 01:10

Yair Halberstadt


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;}
}
like image 43
Ben Avatar answered Oct 17 '22 01:10

Ben