Created
March 30, 2015 14:19
-
-
Save RaccoonDev/11ceb952254c50d00721 to your computer and use it in GitHub Desktop.
Object and Stream Extensions to work with stream and json
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
public static class ObjectExtensions | |
{ | |
public static string GetMessageType(this object obj) | |
{ | |
return obj.GetType().AssemblyQualifiedName; | |
} | |
public static string ToJsonString(this object obj) | |
{ | |
return JsonConvert.SerializeObject(obj); | |
} | |
public static Stream ToJsonStream(this object obj) | |
{ | |
var json = obj.ToJsonString(); | |
return new MemoryStream(Encoding.Default.GetBytes(json)); | |
} | |
} | |
public static class StreamExtensions | |
{ | |
public static string ReadToEnd(this Stream stream) | |
{ | |
var reader = new StreamReader(stream); | |
return reader.ReadToEnd(); | |
} | |
public static T ReadFromJson<T>(this Stream stream) | |
{ | |
var json = stream.ReadToEnd(); | |
return JsonConvert.DeserializeObject<T>(json); | |
} | |
public static object ReadFromJson(this Stream stream, string messageType) | |
{ | |
var type = Type.GetType(messageType); | |
var json = stream.ReadToEnd(); | |
return JsonConvert.DeserializeObject(json, type); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment