Classes created in F# serialized incorrectly in a

2019-07-15 09:20发布

I created a class in FSharp like so:

type Account() = class
    let mutable amount = 0m
    let mutable number = 0
    let mutable holder = ""

    member this.Number
        with get () = number
        and set (value) = number <- value

    member this.Holder
        with get () = holder
        and set (value) = holder <- value

    member this.Amount
        with get () = amount
        and set (value) = amount <- value

end

When I reference the project from my C# WebAPI/MVC application like this

[HttpGet]
public Account Index()
{
    var account = new Account();
    account.Amount = 100;
    account.Holder = "Homer";
    account.Number = 1;
    return account;
}

I am getting the following results. Note that the field name are camelCased.

<Account xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/ChickenSoftware.MVCSerializationIssue">
<amount>100</amount>
<holder>Homer</holder>
<number>1</number>
</Account>

When I create a similar class in C# like this

public class NewAccount
{
    public int Number { get; set; }
    public String Holder { get; set; }
    public int Amount { get; set; }
}

the output is Pascal cased

<NewAccount xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/ChickenSoftware.MVCSerializationIssue.Api.Models">
<Amount>100</Amount>
<Holder>Homer</Holder>
<Number>1</Number>
</NewAccount>    

I first thought it was the Json Serializer (Newtonsoft by default I think), but when I put a break in the controller, I see that the C# class only has its public properties exposed and that the F# class has both the Property and the backing field exposed. I tried to add a "private" keyword to the F# let statements but I got this:

Error   1   Multiple visibility attributes have been specified for this identifier. 'let' bindings in classes are always private, as are any 'let' bindings inside expressions. 

So is there a way that the F# classes can treated the same as C# from Web Api?

1条回答
登录 后发表回答