Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 22nd, 2012  |  syntax: None  |  size: 0.90 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to serialize class type but not the namespace to a Json string using DataContractJsonSerializer
  2. [DataContract]
  3. [KnownType(typeof(Subscriber))]
  4. public class Person { ... }
  5.  
  6. [DataContract]
  7. public class Subscriber : Person { ... }
  8.        
  9. var o = new Subscriber("Fleming");
  10.     var serializer = new DataContractJsonSerializer(typeof(Person));
  11.     serializer.WriteObject(Console.OpenStandardOutput(), o);
  12.        
  13. var o = new Subscriber("Fleming");
  14.     var serializer = new DataContractJsonSerializer(typeof(Subscriber));
  15.     serializer.WriteObject(Console.OpenStandardOutput(), o);
  16.        
  17. {
  18.   "__type":"Subscriber:#My.Custom.Namespace",
  19.   "Index":604455,
  20.   "Name":"Fleming",
  21.   "Id":580540
  22. }
  23.        
  24. {
  25.   "__type":"Subscriber:#",
  26.   "Index":708759,
  27.   "Name":"Fleming",
  28.   "Id":675323
  29. }
  30.        
  31. [DataMember(Name = "__type")]
  32. public string SubclassType
  33. {
  34.     get
  35.     {
  36.         return "Subscriber";
  37.     }
  38.     set { }
  39. }
  40.        
  41. public string __type