This project is read-only.
Serialization and Deserialization

Category:
Others
Description: Use Jason serializer to serialize and deserialize data.
Code:
let SerailizationAndDeserialization() = 
let serializeAndDeserialize (originalValue:'T) =
// Create a serializer, an output stream and serialzie the value
let serializer = DataContractJsonSerializer(typeof<'T>)
let out = new System.IO.MemoryStream()
printfn "input: %A" originalValue
serializer.WriteObject(out, originalValue)

// Get the serialized text
let text = out.ToArray() |> System.Text.Encoding.UTF8.GetString
out.Seek(0L, System.IO.SeekOrigin.Begin) |> ignore
printfn "serialized as: %s" text

let deserialziedValue = serializer.ReadObject out
printfn "deserialized as: %A" deserialziedValue

serializeAndDeserialize (1,2)
serializeAndDeserialize [| 1;2;3 |]
serializeAndDeserialize 1.01

let dict = new System.Collections.Generic.Dictionary()
dict.Add(2, "two")
dict.Add(3, "three")
serializeAndDeserialize dict

Execution Result:
input: (1, 2)
serialized as: {"m_Item1":1,"m_Item2":2}
deserialized as: (1, 2)
input: [|1; 2; 3|]
serialized as: [1,2,3]
deserialized as: [|1; 2; 3|]
input: 1.01
serialized as: 1.01
deserialized as: 1.01
input: seq [[2, two]; [3, three]]
serialized as: [{"Key":2,"Value":"two"},{"Key":3,"Value":"three"}]
deserialized as: seq [[2, two]; [3, three]]

Last edited Sep 14, 2011 at 4:29 AM by ttliu2000, version 1

Comments

Thorium Mar 3, 2012 at 10:44 AM 
Also, check this: http://haacked.com/archive/2012/01/30/hazards-of-converting-binary-data-to-a-string.aspx

Thorium Mar 3, 2012 at 10:40 AM 
http://fssnip.net/1l