Advertisement
Guest User

Serialization Fail

a guest
Mar 12th, 2010
329
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.14 KB | None | 0 0
  1. interface MyInterface
  2. {
  3.     int Property1 { get; set; }
  4.  
  5.     int Property2 { get; set; }
  6. }
  7.  
  8. [Serializable]
  9. [DataContract]
  10. public MyObject1 : MyInterface
  11. {
  12.     [DataMember(Name = "p1")
  13.     public int Property1 { get; set; }
  14.    
  15.     [DataMember(Name = "p2")
  16.     public int Property2 { get; set; }
  17.  
  18.     public MyObject1() {}
  19.  
  20.     public MyObject1(int a, int b) { this.Property1 = a; this.Property2 = b; }
  21. }
  22.  
  23. public MyObject2, ISerializable
  24. {
  25.    public string P1 { get; set; }
  26.  
  27.    public MyInterface M1 { get; set; }
  28.  
  29.    public MyObject2() {}
  30.  
  31.    public MyObject2(SerializationInfo info, StreamingContext context) {}
  32.  
  33.    public void GetObjectData(SerializationInfo info, StreamingContext context)
  34.    {
  35.        info.AddValue("p1", this.P1);
  36.        info.AddValue("m1", this.M1);
  37.    }
  38. }
  39.  
  40.  
  41. //--------
  42. // Code to Serialize looks like this:
  43.  
  44. MyObject2 obj = new MyObject2();
  45. obj1.p1 = 1;
  46. obj1.m1 = new MyObject1(1, 2);
  47.  
  48. DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
  49. MemoryStream ms = new MemoryStream();
  50. serializer.WriteObject(ms, obj);
  51. return Encoding.Default.GetString(ms.ToArray());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement