15

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

Dmitry
  • 1,095
  • 14
  • 21
  • 2
    Closely related question [How do I target attributes for a record class?](https://stackoverflow.com/questions/63778276/how-do-i-target-attributes-for-a-record-class) – Pavel Anikhouski Dec 09 '20 at 17:19

2 Answers2

41

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);
Yair Halberstadt
  • 5,733
  • 28
  • 60
3

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;}
}
Ben
  • 757
  • 4
  • 14
  • 2
    Without a Set or Init modifier, the property will not be initialized. Then how will it differ from the class? – Dmitry Dec 09 '20 at 15:26
  • 1
    Thanks for noticing it should have an init after the get. I will update my code now. – Ben Dec 09 '20 at 16:11