Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
- public override IEnumerable<Type> SupportedTypes
- {
- get
- {
- var list = new List<Type>{ typeof(Foo), typeof(Bar)...};
- return list.AsReadOnly();
- }
- }
- public IDictionary<string, object> GetNonNullProertyValues(object obj)
- {
- var dictionary = new Dictionary<string, object>();
- foreach (var property in obj.GetType().GetProperties())
- {
- var propertyValue = property.GetValue(obj, null);
- if (propertyValue != null)
- {
- dictionary.Add(property.Name, propertyValue);
- }
- }
- return dictionary;
- }
- using System.IO;
- using System.Runtime.Serialization.Json;
- public static class JsonExtensions
- {
- public static string ToJson<T>(this T instance)
- {
- var serializer = new DataContractJsonSerializer(typeof(T));
- using (MemoryStream memoryStream = new MemoryStream())
- {
- serializer.WriteObject(memoryStream, instance);
- memoryStream.Flush();
- memoryStream.Position = 0;
- using (var reader = new StreamReader(memoryStream))
- {
- return reader.ReadToEnd();
- }
- }
- }
- public static T FromJson<T>(this string serialized)
- {
- var serializer = new DataContractJsonSerializer(typeof(T));
- using (MemoryStream memoryStream = new MemoryStream())
- {
- using (StreamWriter writer = new StreamWriter(memoryStream))
- {
- writer.Write(serialized);
- writer.Flush();
- memoryStream.Position = 0;
- return (T)serializer.ReadObject(memoryStream);
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment