Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

json.net

f#

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>]?

like image 747
Brad Collins Avatar asked Nov 25 '15 16:11

Brad Collins


1 Answers

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
like image 129
Brad Collins Avatar answered Sep 30 '22 14:09

Brad Collins