Last active
November 4, 2016 06:25
-
-
Save NickDarvey/5997b9412916f53e5a53bff1fe11c8ac to your computer and use it in GitHub Desktop.
DataContract deserialization of Set<T>
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
using System; | |
using System.Diagnostics; | |
using System.IO; | |
using System.Runtime.Serialization; | |
using static LanguageExt.Prelude; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var mapOfStuff = Map( | |
Tuple("one", "two"), | |
Tuple("three","four")); | |
var setOfStuff = Set("one", "two", "three"); | |
var test = new Test("Hello", mapOfStuff, setOfStuff); | |
var serialized = Serialize(test); | |
Console.WriteLine(serialized); | |
var thing = Deserialize<Test>(serialized); | |
Debug.Assert(thing.SetOfStuff.Count == test.SetOfStuff.Count); | |
Console.Read(); | |
} | |
private static string Serialize(object obj) | |
{ | |
using (MemoryStream memoryStream = new MemoryStream()) | |
using (StreamReader reader = new StreamReader(memoryStream)) | |
{ | |
DataContractSerializer serializer = new DataContractSerializer(obj.GetType()); | |
serializer.WriteObject(memoryStream, obj); | |
memoryStream.Position = 0; | |
return reader.ReadToEnd(); | |
} | |
} | |
private static T Deserialize<T>(string xml) | |
{ | |
using (Stream stream = new MemoryStream()) | |
{ | |
byte[] data = System.Text.Encoding.UTF8.GetBytes(xml); | |
stream.Write(data, 0, data.Length); | |
stream.Position = 0; | |
DataContractSerializer deserializer = new DataContractSerializer(typeof(T)); | |
return (T)deserializer.ReadObject(stream); | |
} | |
} | |
} | |
[DataContract] | |
public class Test | |
{ | |
[DataMember] | |
public string Name { get; private set; } | |
[DataMember] | |
public Map<string, string> MapOfStuff { get; private set; } | |
[DataMember] | |
public Set<string> SetOfStuff { get; private set; } | |
public Test(string name, Map<string, string> mapOfStuff, Set<string> setOfStuff) | |
{ | |
Name = name; | |
MapOfStuff = mapOfStuff; | |
SetOfStuff = setOfStuff; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment