Skip to content

Instantly share code, notes, and snippets.

@secana
Created April 4, 2020 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save secana/a8cfc6248c388deb413fcb94028f892b to your computer and use it in GitHub Desktop.
Save secana/a8cfc6248c388deb413fcb94028f892b to your computer and use it in GitHub Desktop.
F# dict serialization error with SharpYaml
#r "nuget: SharpYaml"
open SharpYaml.Serialization
let serializer = Serializer()
let myRecord1 = {|
dict1 = ["key", "value"] |> dict
dict2 = ["differentKey", "differentValue"] |> dict
|}
let myRecord2 = {|
dict1 = ["key", "value"] |> dict
dict2 = ["key", "value"] |> dict
|}
serializer.Serialize(myRecord1) |> printf "%s\n"
serializer.Serialize(myRecord2) |> printf "%s\n"
// Requires .NET 5 preview installed
// Execute script with: dotnet fsi --langversion:preview serialize.fsx
@secana
Copy link
Author

secana commented Apr 4, 2020

❯ dotnet fsi --langversion:preview .\serialize.fsx
dict1:
  key: value
dict2:
  differentKey: differentValue

dict1:
  *o2: *o3
dict2: &o2
  *o2: *o3

myRecord1 with different key value pairs for the two dictionaries gets serialized correctly. The myRecord2 where both dictionaries contain the same key/value pair, the serialization output is gibberish.

How to get the serialization to work for myRecord2?

@secana
Copy link
Author

secana commented Apr 4, 2020

Note: The problem exists with .NET Core 3.1 and an *.fsproj instead of the fsi, too.

@secana
Copy link
Author

secana commented Apr 5, 2020

With the solution provided by xoof, the final code looks like this:

#r "nuget: SharpYaml"
open SharpYaml.Serialization

// Set "EmitAlias" to false
let settings = SerializerSettings()
settings.EmitAlias <- false

let serializer = Serializer(settings)

let myRecord1 = {|
    dict1 = ["key", "value"] |> dict
    dict2 = ["differentKey", "differentValue"] |> dict
|}

let myRecord2 = {|
    dict1 = ["key", "value"] |> dict
    dict2 = ["key", "value"] |> dict
|}

serializer.Serialize(myRecord1) |> printf "%s\n" 
serializer.Serialize(myRecord2) |> printf "%s\n" 

// Requires .NET 5 preview installed
// Execute script with: dotnet fsi --langversion:preview serialize.fsx

Result:

❯ dotnet fsi --langversion:preview .\serialize.fsx
dict1:
  key: value
dict2:
  differentKey: differentValue

dict1:
  key: value
dict2:
  key: value

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment