- public record User(string Name,DateTime DOB);
Now let's consider a situation where you want to serialize the
User record, as shown in the following.- { "User": "Anu Viswan", "DateOfBirth": "2020-11-20T00:00:00" }
- public record User
- {
- [JsonProperty("User")]
- public string Name{get;init;}
- [JsonProperty("DateOfBirth")]
- public DateTime Dob{get;init;}
- }
- // This is wrong - it sets Attributes to the constructor parameter
- public record User([JsonProperty("User")]string Name,[JsonProperty("DateOfBirth")]DateTime DOB);
- // Simplied code
- public class User : IEquatable<User>
- {
- public string Name
- {
- get;
- init;
- }
- public DateTime DOB
- {
- get;
- init;
- }
- public User([JsonProperty("User")] string Name, [JsonProperty("DateOfBirth")] DateTime DOB)
- {
- this.Name = Name;
- this.DOB = DOB;
- base..ctor();
- }
- }
Solution
The solution lies in specifying the target to which the attribute is applied to. This can be done using the
property:. As noted in Microsoft documentation: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.
Let's rewrite our record again:
- public record User([property:JsonProperty("User")]string Name,[property:JsonProperty("DateOfBirth")]DateTime DOB);
- // Simplied code
- public class User : IEquatable<User>
- {
- [JsonProperty("User")]
- public string Name
- {
- get;
- init;
- }
- [JsonProperty("DateOfBirth")]
- public DateTime DOB
- {
- get;
- init;
- }
- public User(string Name, DateTime DOB)
- {
- this.Name = Name;
- this.DOB = DOB;
- base..ctor();
- }
- }
- var data = new User("Anu Viswan",new DateTime(2020,11,20));
- var serializedData = JsonConvert.SerializeObject(data);
- // Output
- {"User":"Anu Viswan","DateOfBirth":"2020-11-20T00:00:00"}
On a closing note, if you replace
property: with field:, the Attribute would be applied to the backing up field of the property.
Join the conversation! Your thoughts help the community grow.