I found this example at Convert an object to json, and json to object to deserializing string to JSON while passing the type and vice versa.
/// Object to Json
let internal json<'t> (myObj:'t) =
use ms = new MemoryStream()
(new DataContractJsonSerializer(typeof<'t>)).WriteObject(ms, myObj)
Encoding.Default.GetString(ms.ToArray())
/// Object from Json
let internal unjson<'t> (jsonString:string) : 't =
use ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(jsonString))
let obj = (new DataContractJsonSerializer(typeof<'t>)).ReadObject(ms)
obj :?> 't
Context:
For a type Document
[<DataContract>]
type Document = {
[<field: DataMemberAttribute(Name="name")>]
Name: string
[<field: DataMemberAttribute(Name="version")>]
Version: string
}
JSON
let str = """{"name: "test"; version="97234982734"}"""
Question
How to call json
and unjson
functions using my example?
Why are the functions specified as internal?