Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonProperty on C# Records in Constructor [duplicate]

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; }
}
like image 443
Isitar Avatar asked Nov 19 '20 15:11

Isitar


People also ask

What is the use of JsonProperty in C#?

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.

What does JsonProperty attribute do?

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.

How to set JsonProperty name in c#?

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.

Is JsonProperty required?

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.


1 Answers

Per the docs:

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.

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).

like image 95
Jeroen Mostert Avatar answered Sep 19 '22 17:09

Jeroen Mostert