Serializing F# Record type to JSON includes '@

2020-01-29 08:57发布

问题:

The DataContractJsonSerializer creates JSON for F# record types that includes the '@' character after each property name. Does anyone know if it is possible to get JSON that does not have this trailing at symbol?

{"heart_rate@":20,"latitude@":45.0,"longitude@":108.0,"name@":"Rambo"}

Here is the script I use to output this sample

#r "System.Xml"
#r "System.Runtime.Serialization"

open System.Text
open System.Runtime.Serialization.Json
open System.IO

type Update = {
    name: string;
    latitude: decimal;
    longitude: decimal;
    heart_rate: int}

let update = {name = "Rambo"; latitude = 45.0m; longitude = 108.0m; heart_rate = 20}

let serializer = new DataContractJsonSerializer( typeof<Update> )

let stream = new MemoryStream()
let data = serializer.WriteObject(stream, update)
let updateData = stream.ToArray()

let json = (Encoding.UTF8.GetString(updateData))

printfn "%s" json

回答1:

It's using the name of the compiler generated backing fields. You can use DataMemberAttribute to provide your own names.

[<DataContract>]
type Update = {
    [<field: DataMember(Name="name")>]
    name: string;
    [<field: DataMember(Name="latitude")>]
    latitude: decimal;
    [<field: DataMember(Name="longitude")>]
    longitude: decimal;
    [<field: DataMember(Name="heart_rate")>]
    heart_rate: int}


回答2:

Although Daniel's solution will work correctly, it is rather tedious to have to add attributes to every property in the record. It turns out that Json.NET produces more readable JSON out of the box. For my application I do not need to use the DataContractSerializer specifically, so JSON.net it is!



标签: json f#