Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 633
WhiteBoard Avatar asked Jan 07 '14 21:01

WhiteBoard


3 Answers

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). The CLIMutable attribute is intended specifically for serialization and saves from having to prefix each member with mutable.

like image 142
Daniel Avatar answered Nov 15 '22 08:11

Daniel


With the help of DataMemberAttribute you can specify names of the serialized members:

type T = {
    [<field: DataMember(Name="name")>]
    mutable name : string;
    [<field: DataMember(Name="height")>]
    mutable height : int;
}
like image 22
Konrad Kokosa Avatar answered Nov 15 '22 08:11

Konrad Kokosa


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.

like image 31
FremyCompany Avatar answered Nov 15 '22 09:11

FremyCompany