编程语言
首页 > 编程语言> > c#-Json的F#类型正在输出Name @和Name

c#-Json的F#类型正在输出Name @和Name

作者:互联网

我正在使用F#类型,并在WPF窗口的数据源上使用它
并由此生成一个json:

type Customer = { 
                    mutable Name: string ; 
                    mutable Phone: PhoneNumber list
                } 
               and 
                   PhoneNumber = {
                                    mutable Number: string
                                 }

但是输出是这样的:

{"Name@":"Superhero","Phones@":[{"Number@":"111","Number":"111"},{"Number@":"222","Number":"222"},{"Number@":"333","Number":"333"}],"Name":"Superhero","Phones":[{"Number@":"111","Number":"111"},{"Number@":"222","Number":"222"},{"Number@":"333","Number":"333"}]}

如果我将类型更改为:

type Customer = { Name: string ; Telephone: string } 

它输出我期望的Json:

{"Name":"Superhero","Phones":[{"Number":"111"},{"Number":"222"},{"Number":"333"}]}

但是WPF绑定抛出此异常:

A TwoWay or OneWayToSource binding cannot work on the read-only property

这是我用来生成Json C#的代码:

var phonelist = new List<PhoneNumber> { new PhoneNumber("111"),
                                        new PhoneNumber("222"),
                                        new PhoneNumber("333")
                                        };
var fsharpList = Microsoft.FSharp.Collections.ListModule.OfSeq(phonelist);  // TODO: Use a Extension Method

var c = new EntidadesFS.DO.Customer(name: "Superhero", phones: fsharpList);
var json = Newtonsoft.Json.JsonConvert.SerializeObject(c);

为什么会这样呢?
如何仅使用可变属性输出属性名称,而末尾不使用@?
或如何解决?

解决方法:

基于对该问题的宝贵评论,并进行了更多搜索
我能够找到解决方案:

[<CLIMutable>]
[<JsonObject(MemberSerialization = MemberSerialization.OptIn)>]
type Customer = { 
                    [<JsonProperty>] mutable Name: string
                    [<JsonProperty>] mutable Phones: PhoneNumber list
                } 
               and [<CLIMutable>]
                   [<JsonObject(MemberSerialization = MemberSerialization.OptIn)>]
                   PhoneNumber = {
                                    [<JsonProperty>] mutable Number: string
                                 }

或者,甚至更好,如果我将字段保持不变(默认为F#),
我只需要添加[< CLIMutable>]属性:

[<CLIMutable>]
type Customer = { 
                    Name: string
                    Phones: PhoneNumber list
                } 
               and 
                   [<CLIMutable>]                   
                   PhoneNumber = {
                                    Number: string
                                 }

输出:

{"Name":"Superhero","Phones":[{"Number":"111"},{"Number":"222"},{"Number":"333"}]}

现在,这将按预期生成Json,并且还可以与WPF绑定一起很好地工作.

标签:f,json-net,wpf,json,c
来源: https://codeday.me/bug/20191110/2014554.html