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) {}
Output:
{"world":"something"}
Expected output:
{"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; }
}
Compares the specified string to the name of this property. Provides a string representation of the property for debugging purposes. Writes the property to the provided writer as a named JSON object property.
JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.
To set the name of individual properties, use the [JsonPropertyName] attribute. The property name set by this attribute: Applies in both directions, for serialization and deserialization.
You definitely don't need all those @jsonProperty . Jackson mapper can be initialized to sereliazie/deserialize according to getters or private members, you of course need only the one you are using.
Per the docs:
Attributes can be applied to the synthesized auto-property and its backing field by using
property:
orfield:
targets for attributes syntactically applied to the corresponding record parameter.
So you want
record Something([property:JsonProperty("hello")] string world) {}
Without the property:
qualifier, the attribute ends up on the parameter of the generated constructor (which is useful in other scenarios, like nullability).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With