Guest User

Untitled

a guest
Jun 19th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
  2.  
  3. public override IEnumerable<Type> SupportedTypes
  4. {
  5. get
  6. {
  7. var list = new List<Type>{ typeof(Foo), typeof(Bar)...};
  8. return list.AsReadOnly();
  9. }
  10. }
  11.  
  12. public IDictionary<string, object> GetNonNullProertyValues(object obj)
  13. {
  14. var dictionary = new Dictionary<string, object>();
  15.  
  16. foreach (var property in obj.GetType().GetProperties())
  17. {
  18. var propertyValue = property.GetValue(obj, null);
  19. if (propertyValue != null)
  20. {
  21. dictionary.Add(property.Name, propertyValue);
  22. }
  23. }
  24.  
  25. return dictionary;
  26. }
  27.  
  28. using System.IO;
  29. using System.Runtime.Serialization.Json;
  30.  
  31. public static class JsonExtensions
  32. {
  33. public static string ToJson<T>(this T instance)
  34. {
  35. var serializer = new DataContractJsonSerializer(typeof(T));
  36. using (MemoryStream memoryStream = new MemoryStream())
  37. {
  38. serializer.WriteObject(memoryStream, instance);
  39.  
  40. memoryStream.Flush();
  41. memoryStream.Position = 0;
  42.  
  43. using (var reader = new StreamReader(memoryStream))
  44. {
  45. return reader.ReadToEnd();
  46. }
  47. }
  48. }
  49.  
  50. public static T FromJson<T>(this string serialized)
  51. {
  52. var serializer = new DataContractJsonSerializer(typeof(T));
  53. using (MemoryStream memoryStream = new MemoryStream())
  54. {
  55. using (StreamWriter writer = new StreamWriter(memoryStream))
  56. {
  57. writer.Write(serialized);
  58. writer.Flush();
  59.  
  60. memoryStream.Position = 0;
  61.  
  62. return (T)serializer.ReadObject(memoryStream);
  63. }
  64. }
  65. }
  66. }
Add Comment
Please, Sign In to add comment