F #: How to apply the Json.NET [JsonConstructor] attribute to the main constructor?

I am trying to do something in F #, as an example JsonConstructorAttributein the Json.NET documentation :

public class User
{
    public string UserName { get; private set; }
    public bool Enabled { get; private set; }

    public User()
    {
    }

    [JsonConstructor]
    public User(string userName, bool enabled)
    {
        UserName = userName;
        Enabled = enabled;
    }
}

The analogue in F # looks something like this, but I get an error while posting [<JsonConstructor>]:

[<JsonConstructor>] // ERROR! (see below)
type User (userName : string, enabled : bool) =
    member this.UserName = userName
    member this.Enabled = enabled

Mistake

This attribute is not valid for use in this language element.

So how can I decorate the primary constructor [<JsonConstructor>]?

+4
source share
1 answer

Turns out it's pretty easy. Direct the main constructor by placing [<JsonConstructor>]directly in front of the list of primary constructor parameters:

type User [<JsonConstructor>] (userName : string, enabled : bool) =
    member this.UserName = userName
    member this.Enabled = enabled
+5
source

Source: https://habr.com/ru/post/1617477/


All Articles