Skip to content

Question: Serializing records with sets and lists in F# #178

@bhandfast

Description

@bhandfast

I'm using F# and I have trouble packing record types containing sets or lists.

The code below fails with the message:

"System.Runtime.Serialization.SerializationException: Type 'FSI_0003+SetRecord' does not have default (parameterless) public constructor."

I guess I need to write a new custom serializer that packs the values as arrays are packed but I'm not sure how? Any ideas or pointers to where I can find examples?

#r "MsgPack.dll"

type TestRecord = {
    Foo : string;
    Bar: int;
}

type OptionRecord = {
    Foo : string option;
    Bar: int;
}

let serializer = MsgPack.Serialization.SerializationContext.Default

let serializeToMsgPack<'T> (x:'T) = 
    serializer.GetSerializer<'T>().PackSingleObject(x)

// Gives result:

serializeToMsgPack { TestRecord.Foo = "Hello"; Bar = 42 }
serializeToMsgPack { OptionRecord.Foo = Some "Hello"; Bar = 42 }
serializeToMsgPack { OptionRecord.Foo = None; Bar = 42 }

type SetRecord = {
    Foo : string option;
    Bar: Set<int>;
}


// Crashes:
serializeToMsgPack { SetRecord.Foo = Some "Hello"; Bar = Set.empty.Add(42) }


type ListRecord = {
    Foo : string option;
    Bar: int list;
}

// Crashes:

serializeToMsgPack { ListRecord.Foo = Some "Hello"; Bar = [ 1 ] }

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugDetected as bugenhancementRequires or request to feature enhancement

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions