Advertisement
andruhovski

Json Deserialization Example

Dec 9th, 2017
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.71 KB | None | 0 0
  1. [DataContract]
  2.     public class Forex
  3.    
  4. {
  5.         [DataMember]
  6.         public string symbol { get; set; }
  7.         [DataMember]
  8.         public double price { get; set; }
  9.         [DataMember]
  10.         public double bid { get; set; }
  11.         [DataMember]
  12.         public double ask { get; set; }
  13.         [DataMember]
  14.         public int timestamp { get; set; }
  15.     }
  16. }        
  17.  
  18. //-----------------------------
  19. class Program{
  20. private static void Demo()
  21.         {
  22.             HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("put-url-here");
  23.             httpWReq.Method = "GET";
  24.             httpWReq.ContentType = "application/json";
  25.             httpWReq.Timeout = 300000;
  26.             HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.GetResponse();
  27.             List<Forex> jsonResponse = null;
  28.  
  29.             try
  30.             {
  31.                 //Get the stream of JSON
  32.                 Stream responseStream = httpWResp.GetResponseStream();
  33.  
  34.                 //Deserialize the JSON stream
  35.                 using (StreamReader reader = new StreamReader(responseStream))
  36.                 {
  37.                     string r = reader.ReadToEnd();
  38.  
  39.                     //Deserialize our JSON
  40.                     DataContractJsonSerializer sr = new DataContractJsonSerializer(typeof(List<Forex>));
  41.                     MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(r));
  42.                     jsonResponse = (List<Forex>)sr.ReadObject(ms);
  43.                 }
  44.             }
  45.             //Output JSON parsing error
  46.             catch (Exception e)
  47.             {
  48.                 Console.WriteLine(e.Message);
  49.             }
  50.             Console.WriteLine("Loaded items {0}", jsonResponse.Count);
  51.         }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement