I'm trying to do something in F# like the JsonConstructorAttribute
example in 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 analog in F# appears to be something like the following, but I'm getting an error on the placement of [<JsonConstructor>]
:
[<JsonConstructor>] // ERROR! (see below)
type User (userName : string, enabled : bool) =
member this.UserName = userName
member this.Enabled = enabled
The error is
This attribute is not valid for use on this language element
So then, how do I decorate the primary constructor with [<JsonConstructor>]
?
It turns out that it's pretty easy. Target the primary constructor by placing [<JsonConstructor>]
just before the primary constructor's parameter list:
type User [<JsonConstructor>] (userName : string, enabled : bool) =
member this.UserName = userName
member this.Enabled = enabled
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