user1443098
user1443098

Reputation: 7645

F# Generic Function

in piping to/from net objects

I learned that I could do this:

let jsonDeserialize json = JsonConvert.DeserializeObject<Dictionary<System.String, System.String>>(json)

then pipe serialized Json Key/Value pairs into jsonDeserialize. It works well. My next question is can I genericize the call to JsonConvert.DeserializeObject? I want to use this so that I can deserialize to other types with the same function.

I tried

let jsonDeserialize json mytype : 'a  = JsonConvert.DeserializeObject<'a>(json)

but then couldn't figure out how to use it. Given a serialized JSON string I want to

let jsDeser = 
    jsonSerialized
    |> jsonDeserialize Dictionary<string, string>

or something like it, in idiomatic F#

Upvotes: 2

Views: 130

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

In F#, type arguments are specified and passed in angle brackets:

let jsonSerialize<'mytype> json : 'mytype = JsonConvert.DeserializeObject<'mytype> json

let jsDeser = jsonSerialized |> jsonDeserialize<Dictionary<string, string>>

Or, preferably, one doesn't specify them at all, but lets the compiler figure them out from the context:

let jsonSerialize json = JsonConvert.DeserializeObject<'a> json

let jsDeser : Dictionary<string, string> = jsonDeserialize jsonSerialized

NOTE: you have to specify the generic argument on JsonConvert.DeserializeObject, because it has a non-generic overload, which will be selected if you don't specify anything.

Upvotes: 3

Related Questions