简体   繁体   English

使用Json.NET将F#可变变量序列化为JSON会生成重复项

[英]Serialization of F# mutable variable to JSON using Json.NET generates duplicated items

Here is my code: 这是我的代码:

 open Newtonsoft.Json
 open Newtonsoft.Json.Converters

 type T = {
     mutable name : string;
     mutable height : int;
     }

 let a = { name = "abc"; height = 180;}
 a.height  <- 200
 let b = JsonConvert.SerializeObject(a, Formatting.Indented)
 printfn "%s"  b

The output of the code is: 代码的输出为:

{
  "name@": "abc",
  "height@": 200,
  "name": "abc",
  "height": 200
}

How can I avoid the outputs with '@' in the properity? 如何避免正确使用“ @”的输出?

Try this: 尝试这个:

[<CLIMutable>]
[<JsonObject(MemberSerialization=MemberSerialization.OptOut)>]
type T = {
    name : string;
    height : int;
    }

MemberSerialization.OptOut causes only public members to be serialized (skipping private fields which are an implementation detail of records). MemberSerialization.OptOut导致仅将公共成员序列化(跳过专用字段,这些字段是记录的实现详细信息)。 The CLIMutable attribute is intended specifically for serialization and saves from having to prefix each member with mutable . CLIMutable属性专门用于序列化,并且不必为每个成员加上mutable前缀。

Did you try to add attributes [<...>] in front of the property? 您是否尝试在属性前面添加属性[<...>]? Because that attribute will only apply to the property, not to the generated backend. 因为该属性仅适用于该属性,而不适用于生成的后端。 Not sure which attribute JSON.NET reacts to, however. 但是,不确定JSON.NET对哪个属性作出反应。

With the help of DataMemberAttribute you can specify names of the serialized members: 借助DataMemberAttribute您可以指定序列化成员的名称:

type T = {
    [<field: DataMember(Name="name")>]
    mutable name : string;
    [<field: DataMember(Name="height")>]
    mutable height : int;
}

I had the same issue and I had to look eventually this was what worked, after so much digging through Json.Net docs. 我遇到了同样的问题,经过大量研究Json.Net文档后,我最终不得不看这是可行的。

 open System
 open System.Runtime.Serialization

 [<CLIMutable>]
 [<DataContract>]
 type T = {
    [<DataMember>] mutable name : string;
    [<DataMember>] mutable height : int } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM