Guest User

DataContractJsonSerializer example

a guest
Jul 15th, 2016
16,471
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Runtime.Serialization;
  5. using System.Runtime.Serialization.Json;
  6. using System.Text;
  7.  
  8. namespace ConsoleApplication1
  9. {
  10.     [DataContract]
  11.     public class Dog
  12.     {
  13.         [DataMember(IsRequired = true)]
  14.         public string Name { get; set; }
  15.  
  16.         [DataMember]
  17.         public DateTime? BirthDate { get; set; }
  18.  
  19.         /// <summary>
  20.         /// For some reason you might want the serialized name to look different.
  21.         /// </summary>
  22.         [DataMember(Name = "Tags")]
  23.         public List<String> DistinctiveFeatures { get; set; }
  24.     }
  25.  
  26.     class Program
  27.     {
  28.         static void Main(string[] args)
  29.         {
  30.             var dog = new Dog
  31.             {
  32.                 Name = "Fluffy",
  33.                 BirthDate = DateTime.Now,
  34.                 DistinctiveFeatures = new List<string>
  35.                 {
  36.                     "black tail",
  37.                     "green eyes"
  38.                 }
  39.             };
  40.  
  41.             var ser = new DataContractJsonSerializer(typeof(Dog));
  42.             var output = string.Empty;
  43.  
  44.             using (var ms = new MemoryStream())
  45.             {
  46.                 ser.WriteObject(ms, dog);
  47.                 output = Encoding.Unicode.GetString(ms.ToArray());
  48.  
  49.                 // {"BirthDate":"\/Date(1468591293120+0300)\/","Name":"Fluffy","Tags":["black tail","green eyes"]}
  50.             }
  51.  
  52.             using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(output)))
  53.             {
  54.                 var processedDog = (Dog)ser.ReadObject(ms);
  55.  
  56.                 // The two dogs will be the same
  57.             }
  58.         }
  59.     }
  60. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×