Created
July 16, 2010 00:42
-
-
Save OnorioCatenacci/477763 to your computer and use it in GitHub Desktop.
F# fragment for JSON Serialize/Deserialize
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* Borrowed very liberally from | |
https://blogs.msdn.com/b/jomo_fisher/archive/2010/03/06/neat-samples-f-freebase-and-dgml.aspx | |
and | |
http://cs.hubfs.net/forums/permalink/11096/11096/ShowThread.aspx#11096 | |
Many thanks to both those posters for giving me 99% of the starting code | |
*) | |
#r "System.Runtime.Serialization" | |
#r "System.ServiceModel.Web" | |
open System | |
open System.IO | |
open System.Runtime.Serialization | |
[<DataContract>] | |
type rectest = { | |
[<field: DataMember(Name = "id")>] | |
id:int | |
[<field: DataMember(Name = "name")>] | |
name:string} | |
let serialize<'JsonT> i n = | |
let dcs = Json.DataContractJsonSerializer(typeof<'JsonT>) | |
let ms = new IO.MemoryStream() | |
dcs.WriteObject(ms, { id = i; name = n }) | |
ms | |
let deserialize<'JsonT> (jstream:MemoryStream) = | |
let dcs = Json.DataContractJsonSerializer(typeof<'JsonT>) | |
jstream.Seek(0L, IO.SeekOrigin.Begin) |> ignore | |
let r = dcs.ReadObject(jstream) :?> 'JsonT | |
r | |
(* Use: | |
let g = serialize<rectest> 1 "YourName";; | |
let h = deserialize<rectest> g;; | |
let serarray n = | |
[| | |
for idx in 1 .. n -> | |
serialize<rectest> idx "TestValue" | |
|];; | |
let deser_array (a:MemoryStream[]) = | |
[| | |
for idx in 0 .. a.Length-1 -> | |
deserialize<rectest> a.[idx] | |
|];; | |
*) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment